在 XAML 中绑定到图像时处理 null [英] Handling null when binding to an Image in XAML
问题描述
我在 XAML 中有一个 Image 元素.我将 Source 属性绑定到 ViewModel 中的字符串属性.但是,有时该值为空,然后在调试窗口中出现错误.
I have an Image element in XAML. I bind the Source property to a string property in my ViewModel. However, sometimes the value is null and then I get errors in the debug window.
我在这里读到:ImageSourceConverter error for Source=null 我可以如果值为 null,则创建一个转换器以返回 DependencyProperty.UnsetValue.
I read here: ImageSourceConverter error for Source=null that I could make a converter to return DependencyProperty.UnsetValue if the value is null.
现在我想知道是否可以直接在 XAML 中执行此操作?也许通过使用 FallbackValue?我尝试了一些变体,但没有运气.
Now I'm wondering if it is possible to do it directly in XAML? Perhaps by using a FallbackValue? I have tried some variants but with no luck.
这是我在 XAML 中的 Image 元素:
This is my Image element in XAML:
<Image Name="img" Source="{Binding Path=CurrentImageSource}" Stretch="None" />
而 CurrentImageSource 只是 DataContext 上的一个字符串属性.
And CurrentImageSource is just a string property on the DataContext.
错误信息是:System.Windows.Data 错误:23:
The error message is: System.Windows.Data Error: 23 :
无法将 '' 从类型 '' 转换为类型'System.Windows.Media.ImageSource' 用于 'sv-SE' 文化,默认转换;考虑使用 Binding 的 Converter 属性.NotSupportedException:'System.NotSupportedException:ImageSourceConverter 无法从 (null) 转换.
Cannot convert '' from type '' to type 'System.Windows.Media.ImageSource' for 'sv-SE' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: ImageSourceConverter cannot convert from (null).
推荐答案
我将 x:Null 与 TargetNullValue 一起使用,这样您就可以轻松获得空白图像...
I used x:Null with TargetNullValue, that way you get an easy blank image...
<Image Source="{Binding LogoPath, TargetNullValue={x:Null}}" />
这样你就不需要把触发器或 BitmapImages 作为静态资源来处理了.
That way you don't need to mess around with Triggers or BitmapImages as static resources.
这篇关于在 XAML 中绑定到图像时处理 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!