2014-11-24 84 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" />