通过wpf中的属性绑定图像源

Vir*_*rus 7 wpf xaml

我正在尝试使用图像源(.jpg)显示图标.我在视图模型中创建了一个Icon属性,并尝试为其指定图像的路径,但我在视图中看不到任何图像.我尝试将路径转换为位图图像但不起作用.这里有什么我想念的吗?

<StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding Path=Name}"/>
                                <Image Source="{Binding Path=Icon}"></Image>
                            </StackPanel>




BitmapImage img = new BitmapImage();
                    img.BeginInit();
                    img.CacheOption = BitmapCacheOption.OnLoad;
                    img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    img.UriSource = new Uri("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg", UriKind.Absolute);
                    img.EndInit();
                    Icon = img;
Run Code Online (Sandbox Code Playgroud)

Der*_*ter 20

我曾经遇到过这个问题,尽管可能不是最好的解决方案,但以下内容对我有用.

1.将图像添加到项目中,例如:

  • 为项目创建文件夹图像/图标并在其中添加图像.
  • 将图像的构建操作设置为内容(如果更新则复制)

2.创建ImageSource属性:

    public ImageSource YourImage
    {
        get { return _yourImage; }
        set 
        { 
            _yourImage = value;
            NotifyOfPropertyChange(() => YourImage);
        }
    }
Run Code Online (Sandbox Code Playgroud)

(注意:我使用caliburn micro辅助绑定)

3.像这样更新ImageSource:

            if(!string.IsNullOrEmpty("TheImageYouWantToShow"))
            {
                var yourImage = new BitmapImage(new Uri(String.Format("Images/Icons/{0}.jpg", TheImageYouWantToShow), UriKind.Relative));
                yourImage.Freeze(); // -> to prevent error: "Must create DependencySource on same Thread as the DependencyObject"
                YourImage = yourImage;
            }
            else
            {
                YourImage = null;   
            }
Run Code Online (Sandbox Code Playgroud)

4.将source属性绑定到YourImage属性:

(你已经这样做了)