2014-11-24 80 views
0

我的代碼:綁定UriSource對BitmapImage的工作不

<Image Height="100" Width="100" HorizontalAlignment="Left" VerticalAlignment="Top"> 
    <Image.Source> 
     <BitmapImage DecodePixelWidth="100"> 
      <BitmapImage.UriSource> 
       <PriorityBinding> 
        <Binding Path="MyModel1.ImagePath"/> 
        <Binding Path="MyModel2.ImagePath"/> 
       </PriorityBinding> 
      </BitmapImage.UriSource> 
     </BitmapImage> 
    </Image.Source> 
</Image> 

在我的視圖模型,ImagePath的值:

public object ImagePath 
{ 
    get { return new Uri("F:/myFolder/default.png", UriKind.Absolute); } 
} 

的路徑F:/myFolder/default.png存在。我得到錯誤:必須設置屬性'UriSource'或屬性'StreamSource'。這是爲什麼發生?我在哪裏犯錯誤?

回答

0

只需使用普通的string文件路徑,讓它們框架轉換爲BitmapImage元素:

public string ImagePath 
{ 
    get { return new "F:/myFolder/default.png"; } 
} 

...

<Image Height="100" Width="100" HorizontalAlignment="Left" VerticalAlignment="Top"> 
    <Image.Source> 
     <PriorityBinding> 
      <Binding Path="MyModel1.ImagePath"/> 
      <Binding Path="MyModel2.ImagePath"/> 
     </PriorityBinding> 
    </Image.Source> 
</Image> 
+0

回報新 「F:/myFolder/default.png」;返回錯誤:預期類型。 – 2014-11-24 14:35:46

+0

我必須使用BitmapImage,因爲我想使用DecodePixelWidth屬性。 – 2014-11-24 14:40:00

+0

對不起,該屬性應該是'string' ...複製和粘貼錯誤。我現在更新了它。 – Sheridan 2014-11-24 15:16:10

0

的問題是,你不能初始化BitmapImage如果你不沒有UriSourceStreamSource立即可用。您沒有可立即使用的源,因爲您通過Binding提供該源,並且綁定在數據上下文已經設置並且綁定已經處理之前不可用,這不會立即發生。

您需要推遲創建BitmapImage,直到資源可用。您可以使用自定義轉換器做到這一點:

public class ImageConverter : IValueConverter 
{ 
    public ImageConverter() 
    { 
     this.DecodeHeight = -1; 
     this.DecodeWidth = -1; 
    } 

    public int DecodeWidth { get; set; } 
    public int DecodeHeight { get; set; } 

    public object Convert(
     object value, 
     Type targetType, 
     object parameter, 
     CultureInfo culture) 
    { 
     var uri = value as Uri; 
     if (uri != null) 
     { 
      var source = new BitmapImage(); 
      source.BeginInit(); 
      source.UriSource = uri; 
      if (this.DecodeWidth >= 0) 
       source.DecodePixelWidth = this.DecodeWidth; 
      if (this.DecodeHeight >= 0) 
       source.DecodePixelHeight = this.DecodeHeight; 
      source.EndInit(); 
      return source; 
     } 
     return DependencyProperty.UnsetValue; 
    } 

    public object ConvertBack(
     object value, 
     Type targetType, 
     object parameter, 
     CultureInfo culture) 
    { 
     return Binding.DoNothing; 
    } 
} 
<Image Height="100"Width="100" HorizontalAlignment="Left" VerticalAlignment="Top"> 
    <Image.Source> 
    <PriorityBinding> 
     <Binding Path="Model1.ImagePath" Converter="{StaticResource ImageConverter}" /> 
     <Binding Path="Model2.ImagePath" Converter="{StaticResource ImageConverter}" /> 
    </PriorityBinding> 
    </Image.Source> 
</Image> 

...在你的資源放在此:

<l:ImageConverter x:Key="ImageConverter" DecodeWidth="100" />