如何将背景图像设置为Canvas

Sam*_*lex 4 wpf xaml

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)

为什么这个图像不显示在画布背景上

mem*_*eam 6

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

<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


Sea*_*gan 5

您的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)

  • 我宁愿使用转换器.OP在URI上有一个setter.如果他打算改变它,我相信将URI作为字符串保存在ViewModel中并使用转换器进行绑定是更好的选择 (2认同)
  • "你不能将ImageSource绑定到字符串".事实并非如此,因为WPF在这些类型之间具有内置类型转换(由ImageSourceConverter类提供).绑定ImageBrush的`ImageSource`属性或Image控件的`Source`属性只是开箱即用. (2认同)
  • 对真的.你应该尝试一下. (2认同)