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

时间:2013-01-16 12:30:52

标签: 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;

1 个答案:

答案 0 :(得分:20)

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

<强> 1。将图像添加到项目中,例如:

  • 为项目创建文件夹图像/图标,并在那里添加图像。
  • 将图像的构建操作设置为内容(如果较新则复制)

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

(你已经这样做了)

相关问题