Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why WPF Triggers must be declared into a style (even in-line)?

Tags:

wpf

I don't understand why WPF allows me to write both

<Grid>
 <Grid.Triggers>
  <DataTrigger Binding="{Binding HasNeverBeenSeen}" Value="true">
   <Setter Property="Background" Value="Red"/>
  </DataTrigger>
 </Grid.Triggers>
</Grid>

and

<Grid>
 <Grid.Style>
  <Style TargetType="{x:Type Grid}">
   <Style.Triggers>
    <DataTrigger Binding="{Binding HasNeverBeenSeen}" Value="true">
     <Setter Property="Background" Value="Red"/>
    </DataTrigger>
   </Style.Triggers>
  </Style>
 </Grid.Style>
</Grid>

but only the second seems to work. Why is there a Triggers tag to Grid element if we must use a Style?

Thanks

like image 886
Xavier Huppé Avatar asked Jul 09 '14 17:07

Xavier Huppé


1 Answers

Short answer to your question is because this is how it is designed by WPF team.

FrameworkElement.Triggers can only have EventTriggers although property is collection of TriggerBase. It's also clearly stated on MSDN page:

Note that the collection of triggers established on an element only supports EventTrigger, not property triggers (Trigger). If you require property triggers, you must place these within a style or template and then assign that style or template to the element either directly through the Style property, or indirectly through an implicit style reference.

like image 111
Rohit Vats Avatar answered Sep 26 '22 13:09

Rohit Vats