wpf 如何将背景图像设置为 Canvas
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29650471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I set background image to a Canvas
提问by Sam Alex
Wpf Canvas Background image does not display selected image from local path
Wpf Canvas 背景图像不显示从本地路径选择的图像
XAML Code
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 code
MVVM代码
private String _BGImage = @"?C:/Users/sam/Desktop/photo-5.jpg";
public String BGImage
{
get
{
return this._BGImage;
}
set
{
this._BGImage = value;
NotifyPropertyChanged("BGImage");
}
}
Why this image not display on canvas background
为什么这张图片不显示在画布背景上
回答by memory of a dream
or you can try using a converter
或者您可以尝试使用转换器
<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>
and this is the converter
这是转换器
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;
}
}
of course you would still need to check if the string is a valid URI
当然,您仍然需要检查字符串是否是有效的 URI
回答by Sean Cogan
Your viewmodel code for BGImageshould look something like this:
您的视图模型代码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");
}
}
回答by Muds
Well you need to have BGImage as BitmapImage rather than string
那么你需要有 BGImage 作为 BitmapImage 而不是字符串
public BitmapImage BGImage
{
get
{
return new BitmapImage((new Uri(this._BGImage, UriKind.Absolute)));
}
}
If you are changing image dynamically then you have to raise property changed to notify UI
如果您正在动态更改图像,则必须提高属性更改以通知 UI

