WPF: Can I Set IsMouseOver Property of a ChildElement When The Parent Is Moused Over?
Suppose I have a button nested in the Template
of a ListBoxItem
, can I set t开发者_C百科he IsMouseOver
property of the button to true, so that it looks like its moused over?
Just for illustration, the notifications on the top of the window are what I am referring to. Its basically ListBoxItem
's with a TextBlock
and Button
Unfortunately, no. "IsMouseOver" is readonly.
I'm assuming, though, that you have a custom control template for the Button, right? If that's the case, one workaround is to mess with the Tag property of the button. Add a trigger to the ControlTemplate that gets fired when a specific Tag value is set. Then, in the DataTemplate for your ListBoxItems, just set the button's Tag to that specific value when IsMouseOver on the item is true. Below is an example:
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel x:Name="dp" Background="Transparent">
<Button x:Name="btn" DockPanel.Dock="Right" Content="x" Background="Gainsboro">
<Button.Template>
<ControlTemplate TargetType="Button">
<Border x:Name="bd" Padding="2" BorderBrush="Black" BorderThickness="1"
Background="WhiteSmoke">
<ContentPresenter/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bd" Property="Background" Value="LightBlue"/>
</Trigger>
<Trigger Property="Tag" Value="SimulatedMouseOver">
<Setter TargetName="bd" Property="Background" Value="LightBlue"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="bd" Property="Background" Value="Gray"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
<TextBlock Text="{Binding}"/>
</DockPanel>
<DataTemplate.Triggers>
<Trigger SourceName="dp" Property="IsMouseOver" Value="True">
<Setter TargetName="btn" Property="Tag" Value="SimulatedMouseOver"/>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
<s:String>Item1</s:String>
<s:String>Item2</s:String>
<s:String>Item3</s:String>
</ListBox>
精彩评论