Search code examples
c#wpfxamldatatriggervalueconverter

WPF XAML - DataTriggers or ValueConverters? Best practice


I have a Window with a TextBlock. This TextBlock has to show the value "R" if the binded value is 0 or "M" if the binded value is 1.

I have two possibilities:

ValueConverter approach

<TextBlock Binding="{Binding Path=Value, Converter={StaticResource valConverter}}"/>

Where valConverter is an IValueConverter class that returns "M" or "R" if the value is respectively 0 or 1.

[omitted class]

DataTrigger approach

<TextBlock>
    <TextBlock.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding Path=Value}" Value="0">
                    <Setter Property="TextBlock.Text" Value="R"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding Path=Value}" Value="1">
                    <Setter Property="TextBlock.Text" Value="M"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

According to you, what is the best approach?


Solution

  • Converters are Best in this scenario. As the name indicates converter converts the type. In this case you want to convert int to Char, so converters are much suitable. For More Info : ConverterPerformance