Binding to 2nd properties if 1st is "undefined"

I will not copy / paste the whole xaml file. It will be too long to explain this, but here's the interesting part: I got a binding for the Name property

<TextBlock Text="{Binding Name}"/> 

The fact is that sometimes my element does not have the "Name" property. This is not a failure, but I just got empty text in my text block

What I would like to do if the name is empty should be tied to "nothing", just {Binding}. This will display my object name and it will be perfect!

Thanks in advance for any help, and sorry if this is a noobie question :(

+6
source share
4 answers

Here you want PriorityBinding .

In particular, it will look something like this: the exact syntax may require some verification):

  <TextBlock> <TextBlock.Text> <PriorityBinding> <Binding Path="Name"/> <Binding /> </PriorityBinding> </TextBlock.Text> </TextBlock> 

Note that this disappears when the Name property is not available for the associated object; if the Name property has an empty string value, I believe that it will still use this empty value.

+6
source

You can apply the 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> 
+3
source

If you don't need to bind to an object type name, you can use TargetNullValue, which will give you a default value if the bound property is null, for example:

 <TextBlock Text="{Binding Name, TargetNullValue=Default}" /> 

If you really want an object type name, I would suggest writing a converter (implement IValueConverter). Let me know if you want a converter.

0
source

This is theoretically, but ..

I would create a custom style and target all your text blocks. Inside your style, you can set the default text value. If the binding does not cancel the style, your default value will be used.

 Style x:Key="TwitterTextBoxStyle" TargetType="{x:Type TextBox}"> <Setter Property="Text" Value="" /> 
0
source

Source: https://habr.com/ru/post/902208/


All Articles