How to format TargetNullValue property?

1.1k Views Asked by At

This property is implemented on ItemsControl. I need to format or apply style for the string as Italic and grey color.

<ItemsControl ItemsSource="{Binding Source={StaticResource SettingsViewSource}, TargetNullValue= 'No setting available'}" 
                              Background="Transparent" 
                              HorizontalAlignment="Stretch"
                              Focusable="False">
2

There are 2 best solutions below

0
Ramashankar On BEST ANSWER

Define and EmptyDataTemplate if you want to have more control like styling/formatting and switch the datatemplate on based on datatrigger.

For Example

<ItemsControl ItemsSource="{Binding Source={StaticResource SettingsViewSource}}" 
                                  Background="Transparent" 
                                  HorizontalAlignment="Stretch"
                                  Focusable="False">
    <ItemsControl.ItemTemplate>
                 <DataTemplate>
                     //Define your data template here.
                 </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.Style>
        <Style TargetType="ItemsControl">
            <Style.Triggers>
                <Trigger Property="HasItems" Value="false"   >
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <TextBlock Text="This Control is empty"/>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ItemsControl.Style>
<ItemsControl>   

Note: Use HasItems property to determine whether the ItemsControl contains items.

0
nepdev On

Instead of using TargetNullValue, just use a style with a DataTrigger testing for null:

  <Style.Triggers>
      <DataTrigger Binding="{Binding Source={StaticResource SettingsViewSource}}" Value="{x:Null}">
          <Setter Property="FontStyle" Value="Italic" />
          <Setter Property="Background" Value="Gray" />
      </DataTrigger>
  </Style.Triggers>