2012-05-12 27 views
2

我想使用CroppedBitmap。IValueConverter得到空值 - WPF C#

圖像的路徑只在運行時才知道,所以我想通過Binding設置CroppedBitomap.Source。

我發現CroppedBitmap及其源代碼存在已知問題。請參閱:WPF - using CroppedBitmap in DataTemplate

這些鏈接建議使用轉換器。 我試過這樣做,但我總是在Convert函數中獲得空值。

這裏是一個XAML視圖:

<UserControl> 
    <UserControl.Resources> 
     <local:ImageConverter x:Key="imageConverter" /> 
    </UserControl.Resources> 

    <StackPanel> 
     <Label x:Name="testLabel" Content="{Binding Path=Img}"/> 
     <Button x:Name="testButton" Content="{Binding ElementName=testLabel, Path=Content}"/> 

     <Image Stretch="None"> 
      <Image.Source> 
       <CroppedBitmap Source="{Binding ElementName=testLabel, Path=Content, Converter={StaticResource imageConverter}}" SourceRect="10,10,50,50" />    
      </Image.Source> 
     </Image> 
    </StackPanel> 
</UserControl> 

名爲「testLabel」標籤顯示從屬性圖,沒有問題的值。 按鈕「testButton」顯示與「testLabel」相同的值。

這裏是類imageConverter:

public class ImageConverter : IValueConverter 
{ 
     public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 
      FormatConvertedBitmap fcb = new FormatConvertedBitmap(); 
      fcb.BeginInit(); 
      fcb.Source = new BitmapImage(new Uri((string)value)); 
      fcb.EndInit(); 
      return fcb; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
     { 
      throw new NotSupportedException("Cannot convert back"); 
     } 
} 

但是,當我調試功能轉換我看到,名爲「價值」的第一個參數總是得到空。

大師,我需要你的幫助。

+0

如果值爲null,則它與結合的問題,而不是與轉換器... –

+0

我想你是對的。問題是我使用「testButton」相同的綁定,它在那裏工作。圖像控件中是否有不同的數據上下文? –

+0

對於Image控件,DataContext是相同的,但可能不適用於CroppedBitmap本身,因爲它不是可視化樹的一部分...檢查VS中的輸出窗口以查看是否存在綁定錯誤。如果你看到類似「無法找到管理FrameworkElement ...」,這是因爲綁定無法找到DataContext –

回答

1

我有同樣的問題。

我的錯誤是綁定的屬性是錯誤的類型。這是字符串應該是一個枚舉。

沒有生成錯誤。 但在運行時我的(IValueConverter).Convert方法獲得傳遞值= null。

如果出現這種情況 - 檢查綁定...

+0

謝謝..取消了我的自殺計劃 – Sayka