[英]Trigger of button is not working in behind code on WPF
There are 2 part for setting style of button. 按钮的设定方式有2部分。
The 1st is BackgroundProperty
by Style.Setters
. 第1是
BackgroundProperty
通过Style.Setters
。 It's working well. 它运作良好。
The 2nd is BackgroundProperty
by Style.Triggers
which is run by that Mouse is over a button. 第二个是
Style.Triggers
BackgroundProperty
,它由鼠标运行在一个按钮上。 But, It's not working . 但是, 它没有用 。
// 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;
Thanks Ed Plunkett. 谢谢Ed Plunkett。 I added
ControlTemplate
to override the control's background
brush property. 我添加了
ControlTemplate
来覆盖控件的background
画笔属性。
Style style = new Style(typeof(Button));
style.Setters.Add(new Setter(Button.BackgroundProperty, imageSourceOn));
This is the ControlTemplate part what I add: 这是我添加的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)));
And, It is trigger part. 并且,它是触发器部分。
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);
Finally, I set my ControlTemplate
. 最后,我设置了
ControlTemplate
。
template.Triggers.Add(trigger);
setter = new Setter();
setter.Property = Button.TemplateProperty;
setter.Value = template;
style.Setters.Add(setter);
It works well. 它运作良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.