2012-10-24 84 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