Give TextBlock Default Value if result returns null

KeyboardFriendly picture KeyboardFriendly · May 17, 2013 · Viewed 12.4k times · Source

Hello I am trying to give a default value to a textblock if the results returned are null

Here is what I am trying!

All that returns is the String Format I set!

 <TextBlock x:Name="NameTxtBlock" Grid.Column="0" Margin="0,0,40,0" FontFamily="Segoe UI" FontSize="14" Text="{Binding Name, StringFormat='Item Name: {0}'}"  Padding="2">
    <TextBlock.Style>
        <Style TargetType="TextBlock" >                                            
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=NameTxtBlock, Path=Text}" Value="{x:Null}">
                    <Setter Property="FontStyle" Value="Italic"/>
                    <Setter Property="Text" Value="No Name Found" />
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=NameTxtBlock, Path=Text}" Value="{x:Static System:String.Empty}">
                    <Setter Property="FontStyle" Value="Italic"/>
                    <Setter Property="Text" Value="No Name Found" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

Answer

LPL picture LPL · May 17, 2013

You could use TargetNullValue Property. This will return TargetNullValue without StringFormat if the binding returns Null.

<TextBlock Text="{Binding Name, StringFormat='Item Name: {0}', TargetNullValue='No Name Found'}" />