0

我在窗口中有一张图片

  <Image   Source="{Binding Path=MYImage, Converter={StaticResource ResourceKey=imageConverter}}" />

我也尝试过使用值转换器:

 public  class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
                          object parameter, CultureInfo culture)
    {
        try
        {
            return new BitmapImage(new Uri((string)value));
        }
        catch
        {
            return new BitmapImage();
        }
    }

    public object ConvertBack(object value, Type targetType,
                              object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

并为它创建了一个依赖属性。

 public string MYImage
    {
        get { return (string)GetValue(MYImageProperty); }
        set { SetValue(MYImageProperty, value); }
    }
    public static readonly DependencyProperty MYImageProperty=DependencyProperty.Register("PickerImage",typeof(string),typeof(MYClass),new PropertyMetadata("/MYProject;component/pic.png"));

但是当我使用它时,不要显示图像!

4

2 回答 2

0

您不必转换源。

你可以像这样绑定一个字符串:

"/My.Namespace;component/Resources/thatsMyImage.png"

xml:

<Image Source="{Binding Path=MYImage}" />
于 2012-10-24T05:26:46.490 回答
0

这就是我在我的应用程序中解决问题的方式。

  1. 我的应用程序有很多解决方案,每个解决方案都有很多项目。
  2. 我正在使用 WPF 在 VS 2012 上运行 .NET 4.5。
  3. 我的应用结构是:

    我的应用程序

    • 核心解决方案

      -项目A1

      -资源

      -图片

        warning.ico (Build action set to Resource)
        information.ico (Build action set to Resource)
        error.ico (Build action set to Resource)
      

      +项目A2

    • 个人数据库解决方案

      +项目B1

      +项目B2

  4. 我在 CoreSolution 的 ProjectA1 项目中添加了图像(实际图像而不是链接)。我没有更改任何图像的构建操作。编译项目得到ProjectA1.dll。

  5. 在 ProjectB2 的 PersonDatabaseSolution 中,我使用以下代码在后面的代码中引用 error.ico:

        private ImageSource _myImage
        public ImageSource MyImage
        {
         get
         {
          if(_myImage==null)
          {
           uriLoc=new Uri("pack://application:,,,/CoreSolution.ProjectA1;component/Resources/Images/error.ico", UriKInd.Absolute);
           BitmapImage bmImage = new BitmapImage();
           bmImage.BeginInit();
           bmImage.UriSource = uriLoc;
           bmImage.EndInit();
           _myImage=bmImage;
          }
          return _myImage;
         }
        }
    
  6. MyImage 属性绑定在 xaml 中:

     <Image Source="{Binding Path=MyImage}"/>
    

到目前为止,这对我有用。希望它也对其他人有所帮助。

谢谢, RDV

于 2013-08-30T21:11:41.493 回答