Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding to a 2nd properties if the 1st one is "undefined"

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 :(

like image 742
Guillaume Slashy Avatar asked Nov 23 '11 14:11

Guillaume Slashy


2 Answers

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.

like image 145
Dan Bryant Avatar answered Sep 20 '22 18:09

Dan Bryant


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>
like image 27
H.B. Avatar answered Sep 24 '22 18:09

H.B.