Conditional text binding XAML

The way we do this type of thing for MVVM is to create a property in your viewmodel for this. This allows for you to have unit testing for your condition on the viewmodel.

The property in your viewmodel will be the string value that the TextBlock is bound to. The viewmodel at some point will determine the value of that string based on the conditional logic that you need.


You could achieve that with a Style and a DataTrigger:

<TextBlock>
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Text" Value="{Binding FalseText}"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ShowTrueText}" Value="True">
                    <Setter Property="Text" Value="{Binding TrueText}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

An alternative would be to use a MultiBinding with a multi-value converter:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource TextConverter}">
            <Binding Path="TrueText"/>
            <Binding Path="FalseText"/>
            <Binding Path="ShowTrueText"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

The converter would look like this:

public class TextConverter : IMultiValueConverter
{
    public object Convert(
        object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var trueText = (string)values[0];
        var falseText = (string)values[1];
        var showTrueText = (bool)values[2];
        return showTrueText ? trueText : falseText;
    }

    public object[] ConvertBack(
        object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

Tags:

C#

Wpf

Xaml