繁体   English   中英

按钮的触发器在WPF后面的代码中不起作用

[英]Trigger of button is not working in behind code on WPF

按钮的设定方式有2部分。

第1是BackgroundProperty通过Style.Setters 它运作良好。

第二个是Style.Triggers BackgroundProperty ,它由鼠标运行在一个按钮上。 但是, 它没有用

// the 1st BackgroundProperty by Style.Setters
Style style = new Style(typeof(Button));
style.Setters.Add(new Setter(Button.BackgroundProperty, imageSourceOn));

// the 2nd BackgroundPropert by Style.Triggers
Setter setter = new Setter();
setter.Property = Button.BackgroundProperty;
setter.Value = imageSourceOff;
Trigger trigger = new Trigger();
trigger.Property = IsMouseOverProperty;
trigger.Value = true;
trigger.Setters.Add(setter);
style.Triggers.Add(trigger);

Button button = new Button();
button.Margin = new Thickness(0, 5, 80, 5);
button.BorderThickness = new Thickness(0);
button.Name = name;
button.Click += handler;
button.VerticalContentAlignment = VerticalAlignment.Bottom;

// setting Style
button.Style = style;
return button;

谢谢Ed Plunkett。 我添加了ControlTemplate来覆盖控件的background画笔属性。

Style style = new Style(typeof(Button));
style.Setters.Add(new Setter(Button.BackgroundProperty, imageSourceOn));

这是我添加的ControlTemplate部分:

ControlTemplate template = new ControlTemplate(typeof(Button));
FrameworkElementFactory elemFactory = new FrameworkElementFactory(typeof(Border));
elemFactory.Name = "Border";
elemFactory.SetValue(Border.BackgroundProperty, new TemplateBindingExtension(Button.BackgroundProperty));
template.VisualTree = elemFactory;
elemFactory.AppendChild(new FrameworkElementFactory(typeof(ContentPresenter)));

并且,它是触发器部分。

Setter setter = new Setter();
setter.Property = Button.BackgroundProperty;
setter.Value = imageSourceOff;
Trigger trigger = new Trigger();
trigger.Property = IsMouseOverProperty;
trigger.Value = true;
trigger.Setters.Add(setter);

最后,我设置了ControlTemplate

template.Triggers.Add(trigger);
setter = new Setter();
setter.Property = Button.TemplateProperty;
setter.Value = template;
style.Setters.Add(setter);

它运作良好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM