gpt4 book ai didi

c# - WPF 样式按钮 MouseOver 问题

转载 作者:太空狗 更新时间:2023-10-29 17:30:46 25 4
gpt4 key购买 nike

我正在尝试在按钮上制作一个简单的鼠标悬停效果,它确实会在鼠标悬停时改变颜色,但颜色会立即更改为默认按钮背景...我该如何覆盖此行为?

这是我的代码:

Style myBtnStyle = new Style();
Trigger bla = new Trigger() { Property = IsMouseOverProperty, Value = true };
bla.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.Black));
myBtnStyle.Triggers.Add(bla);
button2.Style = myBtnStyle;

最佳答案

根据 this post ,那个花哨的动画是内置的,要删除它,您将需要覆盖 ButtonControlTemplate。幸运的是,这并不难。我用了this post作为源 Material ,并提出了以下 Style 给你的想法。

<Style x:Key="MouseOverButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<ControlTemplate.Resources>
<Style x:Key="ShadowStyle">
<Setter Property="Control.Foreground" Value="LightGray" />
</Style>
</ControlTemplate.Resources>
<Border Name="border" BorderThickness="1" Padding="4,2" BorderBrush="DarkGray" CornerRadius="3" Background="{TemplateBinding Background}">
<Grid >
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Name="contentShadow" Style="{StaticResource ShadowStyle}">
<ContentPresenter.RenderTransform>
<TranslateTransform X="1.0" Y="1.0" />
</ContentPresenter.RenderTransform>
</ContentPresenter>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Name="content"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Beige" />
</Trigger>
</Style.Triggers>
</Style>

更新:如果您执意要在代码中应用 Style 并且您不想使用 ResourceDictionary(可能是更好的方法),您可以加载样式 使用 XamlReader.Load 动态设置:

            const string xaml = @"
<Style xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
TargetType='Button'>
<Setter Property='Template'>
<!--- Omitted For Clarity --->
</Setter>
<Style.Triggers>
<Trigger Property='IsMouseOver' Value='True'>
<Setter Property='Background' Value='Beige' />
</Trigger>
</Style.Triggers>
</Style>";
var encoding = new ASCIIEncoding();
var bytes = encoding.GetBytes(xaml);
var style = (Style)XamlReader.Load(new MemoryStream(bytes));
Button1.Style = style;

关于c# - WPF 样式按钮 MouseOver 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2687271/

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