【问题标题】:Handling null when binding to an Image in XAML在 XAML 中绑定到图像时处理 null
【发布时间】:2012-01-21 18:58:09
【问题描述】:

我在 XAML 中有一个 Image 元素。我将 Source 属性绑定到 ViewModel 中的字符串属性。但是,有时该值为 null,然后在调试窗口中出现错误。

我在这里读到:ImageSourceConverter error for Source=null,如果值为 null,我可以制作一个转换器以返回 DependencyProperty.UnsetValue。

现在我想知道是否可以直接在 XAML 中执行此操作?也许通过使用 FallbackValue? 我尝试了一些变体,但没有运气。

这是我在 XAML 中的图像元素:

<Image Name="img" Source="{Binding Path=CurrentImageSource}" Stretch="None" />

CurrentImageSource 只是 DataContext 上的一个字符串属性。

错误信息是: System.Windows.Data 错误:23:

无法将 '' 从类型 '' 转换为 type 'System.Windows.Media.ImageSource' 用于默认的 'sv-SE' 文化 转换;考虑使用 Binding 的 Converter 属性。 NotSupportedException:'System.NotSupportedException: ImageSourceConverter 无法从 (null) 转换。

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    我将 x:Null 与 TargetNullValue 一起使用,这样您就可以轻松获得空白图像...

    <Image Source="{Binding LogoPath, TargetNullValue={x:Null}}" />
    

    这样您就不需要将触发器或位图图像作为静态资源。

    【讨论】:

      【解决方案2】:

      您可以使用数据触发器check for a null reference

      <Image Name="img" Stretch="None" >
          <Image.Style>
              <Style TargetType="{x:Type Image}">
                  <Setter Property="Source" Value="{Binding CurrentImageSource}" /> 
                  <Style.Triggers>
                      <DataTrigger Binding="{Binding CurrentImageSource}" Value="{x:Null}">
                          <Setter Property="Source" Value="/ImageNullRef;component/errorImage.png" />
                      </DataTrigger>
                  </Style.Triggers>
              </Style>
          </Image.Style>
      </Image>
      

      虽然无法直接测试两个值是否不同,但您可以使用this approach Mike Hillberg blogged about 查看一个值是更大还是更小等。

      【讨论】:

      • 谢谢。我希望有一些更简单的语法(比如设置 FallbackValue),但我想这是不可能的。
      【解决方案3】:

      我没有测试过,但我认为这就是 TargetNullValue 的用途:

      <Image Name="img" Source="{Binding Path=CurrentImageSource, TargetNullValue=/ImageNullRef;component/errorImage.png}" Stretch="None" />
      

      【讨论】:

      • 不错的一个。剪切和粘贴不太奏效。我需要创建一个图像资源 (&lt;BitmapImage x:Key='defaultImage' UriSource='/ImageNullRef;component/errorImage.png' /&gt;),然后像 &lt;Image Name="img" Source="{Binding Path=CurrentImageSource, TargetNullValue={StaticResource defaultImage}}" Stretch="None" /&gt; 那样引用它。有效的答案,我学到了一些东西-> +1
      • 非常好。我喜欢这个。 +1
      【解决方案4】:

      我只是检查了 Sascha Hennig 的答案。它在我这边运行良好。我只是稍作修改(删除图片资源中的/ImageNullRef;&lt;BitmapImage x:Key='defaultImage' UriSource='component/errorImage.png' /&gt;

      【讨论】:

        猜你喜欢
        • 2016-10-03
        • 1970-01-01
        • 1970-01-01
        • 2011-01-25
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多