WPF Binding - Default value for empty string

kroimon picture kroimon · Mar 22, 2013 · Viewed 84.2k times · Source

Is there a standard way to set a default or fallback value for a WPF binding if the bound string is empty?

<TextBlock Text="{Binding Name, FallbackValue='Unnamed'" />

The FallbackValue only seems to kick in when Name is null, but not when it is set to String.Empty.

Answer

iltzortz picture iltzortz · Mar 22, 2013

DataTrigger is the way i do it like this:

<TextBox>
  <TextBox.Style>
        <Style TargetType="{x:Type TextBox}"  BasedOn="{StaticResource ReadOnlyTextBox}">
            <Setter Property="Text" Value="{Binding Name}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Name.Length, FallbackValue=0, TargetNullValue=0}" Value="0">
                    <Setter Property="Text" Value="{x:Static local:ApplicationLabels.NoValueMessage}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>