Hello,
I have made some performance tests with DataTriggers and Converters. For testing purposes I have chosen Visibility property. In first case I have binded Visibility property to IsVisible view model boolean property with standard BooleanToVisibilityConverter converter.
<Border Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}" Background="Blue" />
Next case was written with DataTrigger
<Border Background="Red">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Visibility" Value="Visible" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsVisibleDataTrigger}" Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style&
</Border>
And the last one is the simple binding to Visibility view model property of System.Windows.Visibility type:
<Border Visibility="{Binding Visibility}" Background="Green" />
To test all cases I have run following code in separate thread:
await Task.Factory.StartNew(
() =>
{
int N = 1000000;
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < N; i++)
{
viewModel.IsVisible = !viewModel.IsVisible;
}
timer.Stop();
resultConveter = timer.ElapsedMilliseconds;
timer.Reset();
timer.Start();
for (int i = 0; i < N; i++)
{
viewModel.IsVisibleDataTrigger = !viewModel.IsVisibleDataTrigger;
}
timer.Stop();
resultDataTrigger = timer.ElapsedMilliseconds;
timer.Reset();
timer.Start();
bool isVisible = viewModel.Visibility == Visibility.Visible;
for (int i = 0; i < N; i++)
{
viewModel.Visibility = isVisible ? Visibility.Collapsed : Visibility.Visible;
isVisible = !isVisible;
}
timer.Stop();
resultBinding = timer.ElapsedMilliseconds;
});
Here is results of this testing (lower is better):
As we can see Binding is the fastest, but by using converters with boolean view model property you will make you view model code cleaner.