WPF绑定图像源 [英] WPF Binding Image Source

查看:59
本文介绍了WPF绑定图像源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

maybe stupid question, but I don't know anymore...

我有这样的ViewModel类:

I have ViewModel class like this:

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中的绑定如下所示:

Binding in XAML looks like this:

  <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的内容:

And I set content of ImageSource like this:

MainWindowsViewModel _view = new MainWindowsViewModel();

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

但是它不起作用.我认为问题出在NotifyPropertyChanged中,因为我尝试将制动点放置在setget中. Get在开始时触发了几次,然后set也使用正确的ImageSource触发了,但是之后get不再触发.就像从未发生过任何事情一样.

But it does not work. I think that problem is in that NotifyPropertyChanged, because I tried place brake point in the set and get. Get triggered few times at the start, after then set triggered as well with correct ImageSource, but after then get did not triggered anymore. Like no setting ever happened.

我确实做了很多类似的事情,实际上只是简单的绑定...我不知道为什么这次不起作用.

It's really simply binding that I have done many times similarly...I don't know why it doesn't work this time.

推荐答案

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

You are creating two instances of your MainWindowsViewModel class, one in XAML by

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

和后面的代码中的一个

MainWindowsViewModel _view = new MainWindowsViewModel();

因此,您后面的代码将属性设置为与视图绑定的视图模型实例不同的视图模型实例.

So your code behind sets the property on a different view model instance than the one the view is bound to.

将您的代码更改为此:

var viewModel = (MainWindowsViewModel)DataContext;
viewModel.StatusImage = new BitmapImage(...);

这篇关于WPF绑定图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆