EventSetter doesn't fire for ListView if ItemContainerStyle is style
A relative n00b to WPF. I have a ListView
thus:
<ListView>
<ListView.View>
<GridView>
...
</GridView>
</ListView.View>
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<EventSetter Event="MouseDoubleClick" Handler="ItemDoubleClick"/>
</Style>
</ListView.Resources>
</ListView>
And in my app.xaml I have the following styles:
<Style TargetType="{x:Type ListView}">
<Setter Property="ItemContainerStyle" Value="{DynamicResource ListViewItemStyle}"/>
</Style>
<Style x:Key="ListViewItemStyle" TargetType="{x:Type ListViewItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Border x:Name="Border" Padding="4">
<GridViewRowPresenter x:Name="ItemText"
TextBlock.FontSize="14" TextBlock.Foreground="{x:Static SystemColors.ControlDarkDarkBrush}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True"/>
<Condition Property="IsSelected" Value="False"/>
</MultiTrigger.Conditions>
<Setter TargetName="ItemText" Property="TextBlock.Foreground" Value="{x:Static SystemColors.WindowTextBrush}"/>
</MultiTrigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="Border" Property="Background" Value="{x:Static SystemColors.HighlightBrush}"/>
<Setter TargetName="ItemText" Property="TextBlock.Foreground" Value="{x:Static SystemColors.HighlightTextBrush}"/>
</Trigger>
<开发者_开发技巧;/ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
But once I'm setting the ItemContainerStyle
, the double-click no longer fires. If I remove it, it fires but my ListViewItem
s are not styled.
What am I missing here?
Your local resource is overridden by the application resources style which changes the ListView's ItemContainerStyle property. I would suggest setting the style directly on the ListView.ItemContainerStyle
and basing the style on the existing one:
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}"
BasedOn="{StaticResource {x:Type ListViewItem}}">
<EventSetter Event="MouseDoubleClick" Handler="ItemDoubleClick"/>
</Style>
</ListView.ItemContainerStyle>
(This assumes implicit styling, so either remove the key of the style in your application resources or reference it directly using that key in the BasedOn
property)
To expand on H.B.'s answer, an element can either have an implicit Style or you can set it's Style property directly (what I call an explicit Style), but not both. As soon as you set the Style property on say a ListViewItem, it will no longer use any implicit Styles you have.
Since the ListView.ItemContainerStyle is just an easy way to set the ListViewItem.Style property, it has the same effect of short-circuiting the implicit Style you have defined.
精彩评论