WPF 绑定图像源

2023-12-14

也许是个愚蠢的问题,但我不知道了......

我有这样的 ViewModel 类:

public class MainWindowsViewModel : INotifyPropertyChanged
{
    private ImageSource _img;
    public ImageSource StatusImage
    {
        get { return _img; }
        set
        {
            _img = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName]String propertyName = "")
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

XAML 中的绑定如下所示:

  <Window.DataContext>
    <VM:MainWindowsViewModel />
  </Window.DataContext>
    <Image x:Name="gui_image_status" HorizontalAlignment="Left" Height="26" Margin="144,10,0,0" VerticalAlignment="Top" Width="29" Source="{Binding Path=StatusImage}" />

我这样设置 ImageSource 的内容:

MainWindowsViewModel _view = new MainWindowsViewModel();

        var yourImage = new BitmapImage(new Uri(String.Format("Sources/{0}.png", "red"), UriKind.Relative));
        _view.StatusImage = yourImage;

但这不起作用。我认为问题在于NotifyPropertyChanged,因为我尝试将刹车点放在set and get. Get开始时触发几次,之后触发set使用正确的 ImageSource 也会触发,但之后get没有再触发了。就像没有发生过任何设置一样。

这真的很简单,我已经做了很多次类似的绑定...我不知道为什么这次不起作用。


您正在创建 MainWindowsViewModel 类的两个实例,其中一个在 XAML 中通过

<Window.DataContext>
    <VM:MainWindowsViewModel />
</Window.DataContext>

和一个在代码后面

MainWindowsViewModel _view = new MainWindowsViewModel();

因此,您的后台代码将属性设置在与视图绑定到的视图模型实例不同的视图模型实例上。

将后面的代码更改为:

var viewModel = (MainWindowsViewModel)DataContext;
viewModel.StatusImage = new BitmapImage(...);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF 绑定图像源 的相关文章

随机推荐