通过wpf中的属性绑定图片源 [英] Binding image source through property in wpf

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

问题描述

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

I am trying to display an icon using an image source(.jpg). I create a Icon property in view model and try to assign it the path of the image but I do not see any image in the view. I tried converting the path to Bitmap image but doesn't work. Is there anything I am missing here?

<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;

推荐答案

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

I ran into this myself once and, though maybe not the best solution, the following worked for me.

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

  • 为您的项目创建一个文件夹图像/图标并将图像添加到那里.
  • 将图像的构建操作设置为内容(如果更新则复制)

2.创建 ImageSource 属性:

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

(注:本人使用caliburn micro协助绑定)

(Note: I use caliburn micro to assist in binding)

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 属性:

(你已经这样做了)

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

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