How to implement NullText in a TextBlock with Binding?

I'd recommend implementing an IValueConverter; if the source value is not null or empty, then pass it through to the TextBlock. If the source value is null or empty, then render your chosen text.

public class NullValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string str = (string)value;
        if (str.IsNullOrWhitespace())
        {
            return "No Data";
        }
        return str;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        ... //An empty implementation I expect...
    }
}

However I have just realised that you want to set the style as well... hmmm, probably a DataTrigger that sets the style if the value is 'No Data' required I expect;

<TextBlock Text="{Binding Path=SomeProperty, Converter={StaticResource keyToNullValueConverter}">
    <TextBlock.Triggers>
        <DataTrigger Binding="{Binding Path=Text}" Value="No Data">
            <Setter Property="FontStyle" Value="Italic"/>
        </DataTrigger>
    </TextBlock.Triggers>
</TextBlock>

Something along those lines might work.


I think you don't need to create Converter Class, you can simply write your style code like this.

<Style TargetType="TextBlock">             
<Style.Triggers>                 
<DataTrigger Binding="{Binding ElementName=SerialNumberTextBlock, Path=Text}" Value="{x:Null}">                     
<Setter Property="FontStyle" Value="Italic"/>
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=SerialNumberTextBlock, Path=Text}" Value="{x:Static System:String.Empty}">                     
<Setter Property="FontStyle" Value="Italic"/>
</DataTrigger>
</Style.Triggers>         
</Style> 

Note :- You need to include the system namespace as

xmlns:System="clr-namespace:System;assembly=mscorlib" 

Tags:

C#

Wpf