C# · 12月 27, 2021

c# – WPF样式按钮MouseOver问题

我试图在一个按钮上做一个简单的鼠标悬停效果,当鼠标结束时它会改变颜色,但颜色立即被更改为默认按钮背景…我该如何覆盖此行为?

这是我的代码:

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,这个花哨的动画被内置并被删除,你将需要覆盖你的Button的ControlTemplate.幸运的是,这不是太难了.我使用 this post作为源材料,并提出了以下风格,给你的想法. <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;