首页 > 解决方案 > WPF 图像不会以编程方式更新

问题描述

我有一个应用程序,我希望它在调用命令时加载图像。但问题是没有任何加载,也没有任何中断。我只是看不到我的形象。我还确保将数据上下文设置为我的视图模型。

XAML:

<Image Grid.Column="3" Source="{Binding Path=LoadingImage, Mode=TwoWay}" Width="35" Height="35"/>

视图模型:

    private Image _loadingImage = new Image();
    public Image LoadingImage
    {
      get => _loadingImage;
      set
      {
        _loadingImage = value;
        RaisePropertyChanged(nameof(LoadingImage));
      }
    }

    //Method called by the command... i debugged it and it gets here just fine
    private void GetDirectories()
        {
          FolderBrowserDialog folderBrowseDialog = new FolderBrowserDialog();
          DialogResult result = folderBrowseDialog.ShowDialog();
          if (result == DialogResult.OK)
          {
             //This is how I am getting the image file
             LoadingImage.Source = new BitmapImage(new Uri("pack://application:,,,/FOONamespace;component/Resources/spinner_small.png"));
                //More code below
           }
         }

其他一些设置,我的 .png 文件具有以下属性:

Build Action: Resource
Copy to Output Directory: Copy if newer

这对我来说是头疼的事。我究竟做错了什么?非常感谢。

标签: c#wpf

解决方案


不能将 Image 元素用作另一个 Image 元素的 Source 属性的值。

将属性类型更改为 ImageSource:

private ImageSource _loadingImage;
public ImageSource LoadingImage
{
    get => _loadingImage;
    set
    {
        _loadingImage = value;
        RaisePropertyChanged(nameof(LoadingImage));
    }
}

并像这样分配属性:

LoadingImage = new BitmapImage(
    new Uri("pack://application:,,,/FOONamespace;component/Resources/spinner_small.png"));

除此之外,将绑定的模式设置为双向是没有意义的

<Image Source="{Binding LoadingImage}" />

并且复制到输出目录也是不必要的,因为 Build ActionResource使图像文件成为编译成程序集的程序集资源。


推荐阅读