gpt4 book ai didi

wpf - 如何将背景图像设置为 Canvas

转载 作者:行者123 更新时间:2023-12-04 16:59:47 25 4
gpt4 key购买 nike

WPF Canvas 背景图像不显示从本地路径中选择的图像

XAML代码

  <Canvas x:Name="LayoutRoot" Margin="485,24,0,0" HorizontalAlignment="Left" Width="341" Height="506" VerticalAlignment="Top">
<Canvas.Background>
<ImageBrush ImageSource="{Binding BGImage}"/>
</Canvas.Background>
</Canvas>

MVVM代码
private String _BGImage = @"‪C:/Users/sam/Desktop/photo-5.jpg";

public String BGImage
{
get
{
return this._BGImage;
}
set
{
this._BGImage = value;
NotifyPropertyChanged("BGImage");
}
}

为什么此图片不显示在 Canvas 背景上

最佳答案

或者您可以尝试使用转换器

<UserControl.Resources>
<local:StringToImageConverter x:Key="StringToImageConverter" />
</UserControl.Resources>

...
<Canvas x:Name="LayoutRoot" Margin="485,24,0,0" HorizontalAlignment="Left" Width="341" Height="506" VerticalAlignment="Top">
<Canvas.Background>
<ImageBrush ImageSource="{Binding Path=BGImage, Converter={StaticResource StringToImageConverter}}"/>
</Canvas.Background>
</Canvas>

这是转换器
public class StringToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(string))
{
throw new InvalidOperationException("The value must be a string");
}

return new BitmapImage(new Uri((string)value));
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}

当然,您仍然需要检查字符串是否为有效的URI

关于wpf - 如何将背景图像设置为 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29650471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com