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>
Run Code Online (Sandbox Code Playgroud)
MVVM代码
private String _BGImage = @"?C:/Users/sam/Desktop/photo-5.jpg";
public String BGImage
{
get
{
return this._BGImage;
}
set
{
this._BGImage = value;
NotifyPropertyChanged("BGImage");
}
}
Run Code Online (Sandbox Code Playgroud)
为什么这个图像不显示在画布背景上
或者您可以尝试使用转换器
<UserControl.Resources>
<local:StringToImageConverter x:Key="StringToImageConverter" />
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)
...
<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>
Run Code Online (Sandbox Code Playgroud)
这是转换器
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当然,你仍然需要检查字符串是否是有效的URI
您的viewmodel代码BGImage应如下所示:
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");
}
}
Run Code Online (Sandbox Code Playgroud)