使用模板在hover/单击时更改按钮背景图像

我有一个吨和吨按钮的应用程序,我想用hover/点击效果更加花哨。 我希望可以使用样式模板,所以我不必为每个按钮编写触发器,但我有点陷入这个阶段。

我想你通过这段代码片段了解了我想要实现的目标:

   

和模板文件:

                     

我该如何解决这个问题? 是否有可能以这种方式实现,或者我是否需要使用数百万个触发器来混乱我的代码?

您可以为状态NormalMouseOverPressed (可能更多)定义背景图像的附加属性 。 您可以将这些附加属性用于控件模板中单独的Image控件的Source属性,并在VisualState更改时修改例如Image的Opacity。

示例样式:

  

在具有附加属性集的Button中使用:

  

最后是那些附加属性的定义:

 public static class BackgroundImages { public static readonly DependencyProperty NormalBackgroundImageProperty = DependencyProperty.RegisterAttached("NormalBackgroundImage", typeof(ImageSource), typeof(BackgroundImages)); public static readonly DependencyProperty MouseOverBackgroundImageProperty = DependencyProperty.RegisterAttached("MouseOverBackgroundImage", typeof(ImageSource), typeof(BackgroundImages)); public static readonly DependencyProperty PressedBackgroundImageProperty = DependencyProperty.RegisterAttached("PressedBackgroundImage", typeof(ImageSource), typeof(BackgroundImages)); public static ImageSource GetNormalBackgroundImage(DependencyObject obj) { return (ImageSource)obj.GetValue(NormalBackgroundImageProperty); } public static void SetNormalBackgroundImage(DependencyObject obj, ImageSource value) { obj.SetValue(NormalBackgroundImageProperty, value); } public static ImageSource GetMouseOverBackgroundImage(DependencyObject obj) { return (ImageSource)obj.GetValue(MouseOverBackgroundImageProperty); } public static void SetMouseOverBackgroundImage(DependencyObject obj, ImageSource value) { obj.SetValue(MouseOverBackgroundImageProperty, value); } public static ImageSource GetPressedBackgroundImage(DependencyObject obj) { return (ImageSource)obj.GetValue(PressedBackgroundImageProperty); } public static void SetPressedBackgroundImage(DependencyObject obj, ImageSource value) { obj.SetValue(PressedBackgroundImageProperty, value); } }