wpf - 使用一个鼠标悬停触发器更改多个元素

标签 wpf

如果用户将鼠标悬停在堆栈面板上,我想更改堆栈面板内 2 个元素的颜色。有什么方法可以在 wpf 中这样做,因为我想让我的 c# 代码远离“样式化”。

这是我到目前为止所做的。它只是向堆栈面板内的每个元素添加触发器。但这并不理想,因为您需要将鼠标悬停在每个元素上才能更改其颜色。

                <StackPanel Orientation="Horizontal">
                <StackPanel.Resources>
                    <Style TargetType="{x:Type FrameworkElement}">
                        <Setter Property="Label.Foreground" Value="#FF0296AA" />
                        <Setter Property="Rectangle.Fill" Value="#FF0296AA" />
                        <Style.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Label.Foreground" Value="#FFA6FAFA" />
                                <Setter Property="Rectangle.Fill" Value="#FFA6FAFA" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                    <Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
                    <Style TargetType="{x:Type Rectangle}" BasedOn="{StaticResource {x:Type FrameworkElement}}" />
                </StackPanel.Resources>
                <Label Content="Create an account" VerticalAlignment="Top"  Padding="0,1,5,1" FontSize="13" Height="21" Cursor="Hand"/>
                <Rectangle Height="12" Margin="0,4,0,0" Width="15" RenderTransformOrigin="0.5,0.5">
                    <Rectangle.OpacityMask>
                        <ImageBrush ImageSource="Images/Controls/external-link-mask.png" Stretch="Uniform"/>
                    </Rectangle.OpacityMask>
                </Rectangle>
            </StackPanel>

最佳答案

紧贴您现有的样式,只需将触发器替换为以父 StackPanel 为目标的 DataTrigger

<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type StackPanel}},Path=IsMouseOver}" Value="True">
    <Setter Property="Label.Foreground" Value="#FFA6FAFA" />
    <Setter Property="Rectangle.Fill" Value="#FFA6FAFA" />
</DataTrigger>

此外,您可能希望为 StackPanel 提供一个 Background="Transparent",这样它会对整个区域的鼠标悬停使用react,而不仅仅是在鼠标悬停时恰好在子控件点击区域上方。

关于wpf - 使用一个鼠标悬停触发器更改多个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43844497/

相关文章:

c# - 如何正确地重新映射我的 XAML 命名空间?

wpf - 查看有关ViewModel的知识

wpf - 如何从 ItemsControl 的 Item 后面的代码访问 ItemsControl 的 ItemsSource 元素?

c# - 当项目更改时,WPF ListBox 不更新绑定(bind)项目的值

.net - 为什么 .Net WPF DependencyProperties 必须是类的静态成员

wpf - 如何在 WPF 控件中应用样式?

c# - 如何在 ViewModel 中捕获动态按钮点击

c# - ListView - 从所选项目中获取列值

wpf - 如何通过 XAML 设置 WPF 超链接文本

VirtualizingStackPanel 中的 WPF 4.0 基于像素的滚动