WPF Binding Image Source

南笙酒味 提交于 2019-11-28 14:34:36

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

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

and one in code behind by

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.

Change your code behind to this:

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

I didn't find any problems in your code, but you can try to check few things.

  1. Check that your Image added to the project and set build action of images to Content (copy if newer).
  2. Before updating ImageSource call Freeze method to prevent error: "Must create DependencySource on same Thread as the DependencyObject"

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

Also, there is an easier way to bind image in WPF. You can use string as a source and set a resource path to the binded property:

public string StatusImage  
{
    get { return "/AssemblyName;component/Sources/red.png"; }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!