2

I would like to make a WPF usercontrol that shows a string when and only when the datacontext == null. I'm using the TargetNullValue attribute in binding to display a custom string when the datacontext is null, and that's working as intended. But when the datacontext is non-null, it just shows the ToString value, which I would like to get rid of.

Of course I could solve this easily by using a valueconverter, but I'd like to find a way to solve this with xaml only. Does anyone know a way to do it?

2
  • When value is non-null, what you want to display? Commented Feb 8, 2014 at 11:52
  • @Rohit: In that case I want to display nothing at all Commented Feb 8, 2014 at 11:57

2 Answers 2

4

In case you want TextBlock to be shown only in case binding value is null, you can have trigger in place and set Visibility to Visible when binding value is null and otherwise Collapsed always.

<TextBlock Text="{Binding TargetNullValue=NullValue}">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Visibility" Value="Collapsed"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding}" Value="{x:Null}">
                    <Setter Property="Visibility" Value="Visible"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
Sign up to request clarification or add additional context in comments.

Comments

3

Use a data trigger on {x:Null}. There are many options using styles, data templates etc., depending on taste and needs. For instance:

<DataTemplate x:Key="ShowOnNull">
  <TextBlock x:Name="text"/>

  <DataTemplate.Triggers>
    <DataTrigger Binding="{Binding}" Value="{x:Null}">
      <Setter TargetName="text" Property="Text" Value="your custom string"/>
    </DataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>
...
<ContentPresenter ContentTemplate="{StaticResource ShowOnNull}" 
    Content="{Binding ...}"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.