Wpf画布背景图像不显示本地路径中的选定图像
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");
}
}
为什么此图像不会显示在画布背景上
答案 0 :(得分:6)
或者您可以尝试使用转换器
<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
答案 1 :(得分:5)
BGImage
的viewmodel代码应如下所示:
private ImageSource _BGImage = new BitmapImage(new Uri(@"C:\Users\sam\Desktop\photo-5.jpg", UriKind.Absolute))
public ImageSource BGImage
{
get { return _BGImage; }
set
{
_BGImage= value;
NotifyPropertyChanged("BGImage");
}
}
答案 2 :(得分:0)
你需要将BGImage作为BitmapImage而不是字符串
public BitmapImage BGImage
{
get
{
return new BitmapImage((new Uri(this._BGImage, UriKind.Absolute)));
}
}
如果要动态更改图像,则必须将属性更改为通知UI