There are 2 part for setting style of button.
The 1st is BackgroundProperty
by Style.Setters
. It's working well.
The 2nd is BackgroundProperty
by Style.Triggers
which is run by that Mouse is over a button. 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. I added ControlTemplate
to override the control's background
brush property.
Style style = new Style(typeof(Button));
style.Setters.Add(new Setter(Button.BackgroundProperty, imageSourceOn));
This is the ControlTemplate part what I add:
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
.
template.Triggers.Add(trigger);
setter = new Setter();
setter.Property = Button.TemplateProperty;
setter.Value = template;
style.Setters.Add(setter);
It works well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.