Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

wpf - Handling null when binding to an Image in XAML

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: 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I used x:Null with TargetNullValue, that way you get an easy blank image...

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

That way you don't need to mess around with Triggers or BitmapImages as static resources.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...