【问题标题】:Binding image source through property in wpf通过 wpf 中的属性绑定图像源
【发布时间】:2013-01-16 12:30:52
【问题描述】:

我正在尝试使用图像源 (.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;

【问题讨论】:

  • 你有一个你应该在 Icon 属性中拥有的 Uri 的例子吗?图片是嵌入式资源,还是松散文件,还是在网络上?
  • 它只是我创建的 .jpg 图像。图像存储在我的桌面上。我正在尝试将其绑定到 Icon 属性。
  • Icon包含图片文件的绝对路径?
  • 是的,图片文件的绝对路径
  • 如果它是一个有效的绝对路径,它应该可以开箱即用。无论如何,我建议遵循 Deruijter 在他的回答中给出的解决方案。

标签: wpf xaml


【解决方案1】:

我自己也遇到过一次,虽然可能不是最好的解决方案,但以下方法对我有用。

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

  • 为您的项目创建一个文件夹 images/icons 并在其中添加图像。
  • 将图像的构建操作设置为内容(如果较新则复制)

2。创建 ImageSource 属性:

    public ImageSource YourImage
    {
        get { return _yourImage; }
        set 
        { 
            _yourImage = value;
            NotifyOfPropertyChange(() => YourImage);
        }
    }

(注:我用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;   
            }

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

(你已经这样做了)

【讨论】:

  • 您也可以考虑使用转换器从路径创建 ImageSource。
  • 我们是否必须将此图像添加到解决方案中?我正在尝试从视图模型中执行此操作,可以吗?
  • @slugster 确实,但它会增加一些额外的开销。这是一个不错的选择,但我个人不太喜欢转换器。
  • @Virus 不,您基本上可以随心所欲地检索图像。尝试使用新的 Uri 方法,看看它可以为您做什么。您还可以进一步创建一个 ImageHandler 类来为您完成这些事情。然后更新你的ImageSource,例如,你可以说YourImage = ImageHandler.Get("icon", "TheImageYouWantToShow");
  • 我正在关注这个东西,但我仍然看不到我视图中的图像。此外,在我的代码中,图标返回类型是 ImageSource,元数据显示“不支持”异常。
猜你喜欢
  • 1970-01-01
  • 2015-09-21
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-22
相关资源
最近更新 更多