WPF XAML - DataTriggers or ValueConverters? Best practice

I have a window with a TextBlock . This TextBlock should show the value "R" if the associated value is 0 or "M" if the associated value is 1.

I have two options:

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 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> 

In your opinion, what is the best approach?

+1
c # wpf xaml valueconverter datatrigger
source share
2 answers

Converters are the best in this scenario. As the name indicates, the converter converts the type. In this case, you want to convert int to Char, so converters are very suitable. For more information: ConverterPerformance

+2
source share

In most scenarios, triggers can do the same job as any converter, but Converters can have user / business logic.

One limitation of Triggers is that Setters in your DataTriggers can change the properties of your user interface elements; therefore, you cannot update your ViewModels property with triggers where Converters win, remember the ConvertBack method.

So, briefly Triggers can only perform OneWay operations, while Converters can only perform TwoWay operations

+4
source share

All Articles