2012-10-24 45 views
0

不工作我在窗口数据绑定图像UriSource

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

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

+0

你有没有在MyImage中尝试过相对路径。 –

回答

0

您不必转换源代码。

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

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

XAML:

<Image Source="{Binding Path=MYImage}" /> 
+0

谢谢,我使用这个但不适用于我:( –

+0

什么说在Visual Studio中的输出窗口? – David

+0

为MYImage设置值,但不显示当我使用此字符串的文本块的文本不显示文本对于文本块:( –

0

这是我解决了这个问题在我的应用程序。

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

    MyApplication的

    • CoreSolution

      -ProjectA1

      -resources

      - 图像

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

      + ProjectA2

    • PersonDatabaseSolution

      + ProjectB1

      + ProjectB2

  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