How to use DataTrigger to set property defined in ViewModel in WPF

I am writing a XAML file that uses a DataTrigger to set a property in a ViewModel. The ViewModel class is defined as:

public class ShellModel : INotifyPropertyChanged { public Brush ForegroundBrush { get; set; } .................... } 

I want to use a DataTrigger in View.xaml to set the ForegroundBrush property. I wrote XAML:

 <StatusBar Name="statusBar" Grid.Row="3"> <StatusBarItem> <StatusBarItem.Style> <Style> <Style.Triggers> <DataTrigger Binding="{Binding HasError}" Value="True"> <Setter Property="ForegroundBrush" Value="Red" /> </DataTrigger> <DataTrigger Binding="{Binding HasError}" Value="False"> <Setter Property="ForegroundBrush" Value="Black" /> </DataTrigger> </Style.Triggers> </Style> </StatusBarItem.Style> <TextBlock Name="statusBarMessage" Foreground="{Binding ForegroundBrush}" Text="{Binding StatusMessage}"></TextBlock> </StatusBarItem> ........................ 

This does not compile. When i changed

  <Setter Property="ForegroundBrush" Value="Black" /> 

to

  <Setter Property="ShellModel.ForegroundBrush" Value="Black" /> 

this gives me an error:

The dependency property field is missing ....

How do I write this so that the DataTrigger can set the ForegroundBrush property in the ViewModel?

+8
wpf datatrigger
source share
1 answer

The retailers of your DataTriggers should only change the properties of your user interface elements (and they only work with DependencyProperties).
Set the Foregound property of the Foregound property directly and set the TargetType of the style. This should help.

  <Style TargetType="{x:Type StatusBarItem}"> <Style.Triggers> <DataTrigger Binding="{Binding HasError}" Value="True"> <Setter Property="Foreground" Value="Red" /> </DataTrigger> <DataTrigger Binding="{Binding HasError}" Value="False"> <Setter Property="Foreground" Value="Black" /> </DataTrigger> </Style.Triggers> </Style> 

Having visual presentation information in your ViewModel is usually not a good idea.

+6
source share

All Articles