首页 文章

WPF绑定图像源

提问于
浏览
1

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

我有这样的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 ,因为我试过在 setget 中放置制动点 . Get 在开始时触发了几次,之后 set 也触发了正确的ImageSource,但之后 get 没有再触发 . 就像没有任何环境发生过 .

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

2 回答

  • 3

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

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

    一个代码在后面

    MainWindowsViewModel _view = new MainWindowsViewModel();
    

    因此,您的代码在不同的视图模型实例上设置属性,而不是视图绑定的属性 .

    将您的代码更改为:

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

    我没有在你的代码中发现任何问题,但你可以尝试检查一些事情 .

    • 检查您的图像是否已添加到项目中,并将图像的构建操作设置为内容(如果较新则复制) .

    • 在更新ImageSource之前调用Freeze方法以防止错误:“必须在与DependencyObject相同的线程上创建DependencySource”

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

    此外,还有一种更简单的方法来绑定WPF中的图像 . 您可以使用字符串作为源并设置binded属性的资源路径:

    public string StatusImage  
    {
        get { return "/AssemblyName;component/Sources/red.png"; }
    }
    

相关问题