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

标签 wpf xaml

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/

相关文章:

c# - 带有 TextBlock 的 BulletDecorator 不显示 Unicode 字符

wpf - 如何像使用项目控件一样根据数据类型启用自动 DataTemplate 选择?

c# - 如何为 x :Static 设置后备值

c# - 我最快什么时候可以关闭窗口?

c# - ownerType 不是 DependencyObject 的 DependencyProperty 有什么用?

c# - 如何在 C# Silverlight App 中使字符串值从一个区域访问到另一个区域

c# - 如何在WPF中绘制这条路径?

asp.net - 用 HTML5 替换桌面 WPF 应用程序

c# - WPF中基于RowStyle的CellStyle

c# - 无法将 WP 8.1 应用程序部署到移动设备