UriSource绑定到BitmapImage不起作用

时间:2014-11-24 14:23:31

标签: wpf xaml data-binding 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>

在我的viewmodel中,ImagePath的值:

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

路径F:/myFolder/default.png存在。我收到错误:必须设置属性'UriSource'或属性'StreamSource'。为什么会这样?我在哪里弄错了?

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

问题是,如果您没有BitmapImageUriSource立即可用,则无法初始化StreamSource。您没有立即可用的源,因为您是通过Binding提供的,并且在设置数据上下文并且已经处理绑定之后绑定不可用,这不会立即发生。< / p>

您需要推迟创建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" />