Reputation: 3624
I won't copy/paste my whole xaml file. It will be too long to explain it but here is what is interesting : I got a Binding of a Property "Name"
<TextBlock Text="{Binding Name}"/>
The thing is that sometimes, my item doesn't have a "Name" property. It doesn't crash but I simply got an empty Text in my TextBlock
What I would to do, if Name is empty, is to be binded to "nothing", just {Binding}. This will display my Object name and it will be perfect !
Thanks in advance for any help, and sorry if it is a noobie question :(
Upvotes: 8
Views: 1637
Reputation: 27495
What you want here is a PriorityBinding.
In particular, it would look something like (exact syntax may need some verification):
<TextBlock>
<TextBlock.Text>
<PriorityBinding>
<Binding Path="Name"/>
<Binding />
</PriorityBinding>
</TextBlock.Text>
</TextBlock>
Note that this specifically falls back when the Name property is not available on the object being bound; if the Name property has an empty string value, I believe it will still use that empty value.
Upvotes: 7
Reputation: 184506
You can apply a style with a DataTrigger
:
<TextBlock>
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Text" Value="{Binding Name}"/>
<Style.Triggers>
<!-- In this binding you could inject a converter which checks for more than null -->
<DataTrigger Binding="{Binding Name}" Value="{x:Null}">
<Setter Property="Text" Value="{Binding}"/>
</DataTrigger>
<Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
Upvotes: 3
Reputation: 6433
This is theoretical but..
I would create a custom style and target all of your textblocks. Inside your style, you could set a default text value. If your binding doesn't override the style, your default value will be used.
Style x:Key="TwitterTextBoxStyle" TargetType="{x:Type TextBox}">
<Setter Property="Text" Value="" />
Upvotes: 0
Reputation: 3418
If you don't have to bind to the object type name you could use TargetNullValue which will give you a default value if the bound property is null, like this:
<TextBlock Text="{Binding Name, TargetNullValue=Default}" />
If you really want the object type name I would suggest writing a Converter (implement IValueConverter). Let me know if you want a sample converter.
Upvotes: 0