在XAML绑定到图像时处理空 [英] Handling null when binding to an Image in XAML
问题描述
我在XAML的图像元素。我Source属性为一个字符串属性绑定在我的视图模型。但是,有时值为null,然后我在调试窗口中出现错误。
我读到这里: WPF ImageSourceConverter错误源=空我可以使一个转换器,返回DependencyProperty.UnsetValue如果值是空
现在我想知道是否有可能直接在XAML中呢?也许用FallbackValue?
我曾尝试一些变种,但没有运气。
这是XAML中我的形象元素:
<图像名称=IMG来源={绑定路径= CurrentImageSource}拉伸=无/>
和CurrentImageSource是刚上的DataContext的字符串属性。
该错误信息是:
System.Windows.Data错误:23:
不能'从类型'输入转换
System.Windows.Media.ImageSource为SV-SE文化与默认
转换;考虑使用绑定的转换器属性。
NotSupportedException异常:的System.NotSupportedException:
ImageSourceConverter不能从(空)转换。
块引用>解决方案您可以检查空引用使用数据触发:
<图像名称=IMG拉伸=无>
< Image.Style>
<风格的TargetType ={X:输入图像}>
< setter属性=源VALUE ={结合CurrentImageSource}/>
< Style.Triggers>
< DataTrigger绑定={结合CurrentImageSource}VALUE ={X:空}>
< setter属性=源VALUE =/ ImageNullRef;组件/ errorImage.png/>
< / DataTrigger>
< /Style.Triggers>
< /样式和GT;
< /Image.Style>
< /图像>虽然它不能直接两个值是否不同的测试,你可以看到一个值是否大于或小于等使用的this方法麦克Hillberg在博客。
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.
I read here: WPF ImageSourceConverter error for Source=null that I could make a converter to return DependencyProperty.UnsetValue if the value is null.
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.
This is my Image element in XAML:
<Image Name="img" Source="{Binding Path=CurrentImageSource}" Stretch="None" />
And CurrentImageSource is just a string property on the DataContext.
The error message is: System.Windows.Data Error: 23 :
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).
解决方案You can check for a null reference using a data trigger:
<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>
Whilst it is not possible to test directly whether two values differ, you can see whether a value is greater or smaller, etc. using this approach Mike Hillberg blogged about.
这篇关于在XAML绑定到图像时处理空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!