How do I define a DataTrigger
for a StackPanel
? It does have a Trigger
property, but defining a trigger here gives the following error on Initialize when starting the application:
Failed object initialization (ISupportInitialize.EndInit). Triggers collection members must be of type EventTrigger. ....
This is given from the following simple DataTrigger
:
<StackPanel x:Name="PersonPanel" DataContext="{Binding CurrentPerson}">
<TextBlock Text="{Binding Id}" />
<TextBlock Text="{Binding Name}" />
<StackPanel.Triggers>
<DataTrigger Binding="{Binding Id}" Value="1">
<Setter TargetName="PersonPanel" Property="StackPanel.Background" Value="Green" />
</DataTrigger>
</StackPanel.Triggers>
</StackPanel>
This is my first Trigger
ever, so what do I do wrong? Should I define the Trigger
elsewhere?
A DataTrigger allows you to set property values when the property value of the data object matches a specified Value. For example, if you are displaying a list of Employee objects, you may want the foreground color to be different based on each Employee's current attendance.
There are five types of triggers supported by WPF; they are: Property Trigger. Data Trigger. MultiTrigger.
The WPF styling and templating model enables you to specify triggers within your Style. Essentially, triggers are objects that enable you to apply changes when certain conditions (such as when a certain property value becomes true , or when an event occurs) are satisfied.
Triggers allow you to express actions declaratively in XAML that change the appearance of controls based on events or property changes. In addition, state triggers, which are a specialized group of triggers, define when a VisualState should be applied.
Try something like this
<Window.Resources>
<Style x:Key="spStyle" TargetType="StackPanel">
<Setter Property="StackPanel.Background" Value="Red" />
<Style.Triggers>
<DataTrigger Binding="{Binding Id}" Value="1">
<Setter Property="StackPanel.Background" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel x:Name="PersonPanel" Style="{StaticResource spStyle}" DataContext="{Binding CurrentPerson}">
<TextBlock Text="{Binding Id}" />
<TextBlock Text="{Binding Name}" />
</StackPanel>
try this:
<TextBlock Text="{Binding Id}">
<TextBlock.Style>
<Style>
<Style.Triggers>
<Trigger Property="TextBlock.Text" Value="1">
<Setter TargetName="PersonPanel" Property="StackPanel.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With