gpt4 book ai didi

.net - WPF 按钮样式触发器

转载 作者:行者123 更新时间:2023-12-02 00:21:23 24 4
gpt4 key购买 nike

我被 WPF 中的样式困住了。当用户将鼠标悬停在按钮上时,我需要更改背景渐变,但我不知道如何进行更改。这是我到目前为止的代码:

    <Style x:Key="Button_Green" TargetType="{x:Type Button}">
<Setter Property="FontSize" Value="11" />
<Setter Property="Foreground" Value="White"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="2" BorderBrush="#387f38" BorderThickness="1">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF5BB75B" Offset="0" />
<GradientStop Color="#FF449B44" Offset="1" />
</LinearGradientBrush>
</Border.Background>
<ContentPresenter x:Name="ButtonContentPresenter" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF5BB75B" Offset="0" />
<GradientStop Color="#FF398239" Offset="1" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Cursor" Value="Hand" />
</Trigger>
</Style.Triggers>
</Style>

鼠标光标正常变化,但背景渐变没有变化。

最佳答案

您需要将 setter 的目标设置为您在 ControlTemplate 中定义的 Border 元素。目前,它针对 Button 本身的 Background 属性,该属性被您的自定义 ControlTemplate 隐藏。

<Style x:Key="Button_Green" TargetType="{x:Type Button}">
<Setter Property="FontSize" Value="11" />
<Setter Property="Foreground" Value="White"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="MyBackgroundElement" CornerRadius="2" BorderBrush="#387f38" BorderThickness="1">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF5BB75B" Offset="0" />
<GradientStop Color="#FF449B44" Offset="1" />
</LinearGradientBrush>
</Border.Background>
<ContentPresenter x:Name="ButtonContentPresenter" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="MyBackgroundElement" Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FF5BB75B" Offset="0" />
<GradientStop Color="#FF398239" Offset="1" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Cursor" Value="Hand" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

在这里,我向 Border 元素添加了一个 x:Name 属性,以便可以使用 TargetName 属性引用它 二传手

关于.net - WPF 按钮样式触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10777423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com