首页 > 解决方案 > 更改父事件的属性

问题描述

当鼠标悬停在按钮本身上时,我正在尝试更改按钮内容内的边框属性。

这对我不起作用,我想知道为什么,请帮忙?

<Style x:Key="ButtonGenericStyle" TargetType="{x:Type Button}">
        <Setter Property="Width" Value="200"></Setter>
        <Setter Property="Height" Value="35"></Setter>
        <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
        <Setter Property="VerticalContentAlignment" Value="Stretch"></Setter>
        <Setter Property="Padding" Value="0"></Setter>
        <Setter Property="BorderThickness" Value="0.6"></Setter>
        <Setter Property="BorderBrush" Value="#333"></Setter>
        <Setter Property="Cursor" Value="Hand"></Setter>
    </Style>

        <Style x:Key="AddButtonStyle" BasedOn="{StaticResource ButtonGenericStyle}" TargetType="{x:Type Button}">
        <Setter Property="Content">
            <Setter.Value>
                <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="auto"></ColumnDefinition>
                        <ColumnDefinition Width="*"></ColumnDefinition>
                        <ColumnDefinition Width="Auto"></ColumnDefinition>
                    </Grid.ColumnDefinitions>
                    <Image Width="24" Margin="5,0,0,0" Source="/Images/AddNew.png"></Image>
                    <TextBlock Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center" Text="{x:Static local:GenericGridResources.AddButtonText}"></TextBlock>
                    <Border x:Name="borderAdorner" Grid.Column="2" Width="5" Background="#00C176">
                        <Border.Style>
                            <Style TargetType="{x:Type Border}">
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=IsMouseOver}" Value="True">
                                        <Setter Property="Background" Value="Red"></Setter>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </Border.Style>
                    </Border>
                </Grid>
            </Setter.Value>
        </Setter>
    </Style>

谢谢

编辑:我已经将填充设置为 10 并将对齐更改为中心以确保我的按钮没有被覆盖。

此外,我通过 DataTrigger 绑定处的转换器进行了调试,发送的值是按钮。仍然边框背景不会改变。

***** 我在帖子中将 AncestorType 从 Image 更改为 Button。我从许多测试中复制了一个错误的代码。回答祖先Tyoe应该是父母的人是完全正确的感谢和道歉。**

标签: wpfxamldatatrigger

解决方案


如果你想让鼠标在按钮上工作,那么祖先类型应该是按钮:

 <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=IsMouseOver}" Value="True">
                                    <Setter Property="Background" Value="Red"></Setter>
                                </DataTrigger>

事实上,你的边界有一个兄弟姐妹,它是一个图像。Findancestor 将查找视觉树,并且边框不是图像的子级。

当用户将鼠标悬停在按钮上时,您还需要确保内部有可测试的内容或作为背景。我之所以提到这一点,是因为您的 ButtonGenericStyle 的作用并不完全清楚。


推荐阅读