You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF C#中为动态创建的按钮添加鼠标悬停效果

用C#动态创建带自定义鼠标悬停效果的WPF按钮

你在XAML里的实现思路完全正确——通过重写控件模板移除默认样式,再用触发器实现悬停效果,这套逻辑在C#代码里同样适用,只是需要用代码构建对应的Style、ControlTemplate和Trigger组件。

以下是完整的实现代码:

// 定义按钮的Style,目标类型必须为Button
var buttonStyle = new Style(typeof(Button));

// 设置按钮默认属性
buttonStyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Colors.DarkGreen)));
buttonStyle.Setters.Add(new Setter(Button.ForegroundProperty, new SolidColorBrush(Colors.White)));
buttonStyle.Setters.Add(new Setter(Button.FontSizeProperty, 17.0));
buttonStyle.Setters.Add(new Setter(Button.HeightProperty, 40.0));
buttonStyle.Setters.Add(new Setter(Button.CursorProperty, Cursors.Hand));
buttonStyle.Setters.Add(new Setter(Button.MarginProperty, new Thickness(20)));

// 构建自定义ControlTemplate,替换按钮默认模板
var controlTemplate = new ControlTemplate(typeof(Button));
// 创建模板根节点Border
var borderFactory = new FrameworkElementFactory(typeof(Border));
// 将Border的Background绑定到按钮的Background属性
borderFactory.SetBinding(Border.BackgroundProperty, new Binding("Background") { RelativeSource = RelativeSource.TemplatedParent });

// 创建ContentPresenter用于显示按钮内容
var contentPresenterFactory = new FrameworkElementFactory(typeof(ContentPresenter));
contentPresenterFactory.SetValue(ContentPresenter.HorizontalAlignmentProperty, HorizontalAlignment.Center);
contentPresenterFactory.SetValue(ContentPresenter.VerticalAlignmentProperty, VerticalAlignment.Center);
contentPresenterFactory.SetBinding(ContentPresenter.MarginProperty, new Binding("Padding") { RelativeSource = RelativeSource.TemplatedParent });

// 将ContentPresenter添加到Border下
borderFactory.AppendChild(contentPresenterFactory);
controlTemplate.VisualTree = borderFactory;

// 将自定义模板赋值给Style
buttonStyle.Setters.Add(new Setter(Button.TemplateProperty, controlTemplate));

// 添加鼠标悬停触发器
var mouseOverTrigger = new Trigger();
mouseOverTrigger.Property = Button.IsMouseOverProperty;
mouseOverTrigger.Value = true;
mouseOverTrigger.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush(Colors.Green)));
buttonStyle.Triggers.Add(mouseOverTrigger);

// 创建按钮并应用Style
Button button = new Button();
button.Content = "LOGIN";
button.Style = buttonStyle;

// 将按钮添加到容器(例如Window的Grid或其他布局控件)
yourContainer.Children.Add(button);

核心注意事项:

  • Style的TargetType必须指定为Button:你之前的代码错误地使用了Border作为Style目标,这无法作用于按钮本身的样式。
  • 必须重写ControlTemplate:默认按钮的悬停背景是内置在系统模板中的,只有替换模板才能完全移除默认效果,让自定义的Background和触发器生效。
  • 触发器监听IsMouseOver属性:通过Trigger捕捉鼠标悬停状态,动态修改按钮背景色。

这样实现的按钮,效果和你在XAML中编写的完全一致。

内容的提问来源于stack exchange,提问作者KANAYO AUGUSTIN UG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 03:14:53