当鼠标hover在按钮WPF上时如何制作一个改变图像的图像按钮?
我正在尝试制作一个图像按钮,当鼠标hover在按钮上时会改变图像,我尝试了一些东西
这是我尝试的最后一件事,但它不起作用:
我想只使用XAML,没有cs文件谢谢
您的触发器将应用于StackPanel
。 它需要在ControlTemplate
上设置
尝试:
在这种情况下。 您可以使用Trigger
来设置Image
的源,从而无需在多个UI元素上切换Visibility
。
就像是:
您将需要一个帮助程序类来附加每个按钮状态的图像源属性和按钮的样式。 将帮助程序类放在WPF项目的Helpers
文件夹中。
助手class
public static class ImageLoader { public static ImageSource GetDefaultImage(DependencyObject obj) { return (ImageSource)obj.GetValue(DefaultImageProperty); } public static void SetDefaultImage(DependencyObject obj, ImageSource value) { obj.SetValue(DefaultImageProperty, value); } public static readonly DependencyProperty DefaultImageProperty = DependencyProperty.RegisterAttached( "DefaultImage", typeof(ImageSource), typeof(ImageLoader), new UIPropertyMetadata(null)); public static ImageSource GetHoverImage(DependencyObject obj) { return (ImageSource)obj.GetValue(HoverImageProperty); } public static void SetHoverImage(DependencyObject obj, ImageSource value) { obj.SetValue(HoverImageProperty, value); } public static readonly DependencyProperty HoverImageProperty = DependencyProperty.RegisterAttached( "HoverImage", typeof(ImageSource), typeof(ImageLoader), new UIPropertyMetadata(null)); public static ImageSource GetDisabledImage(DependencyObject obj) { return (ImageSource)obj.GetValue(DisabledImageProperty); } public static void SetDisabledImage(DependencyObject obj, ImageSource value) { obj.SetValue(DisabledImageProperty, value); } public static readonly DependencyProperty DisabledImageProperty = DependencyProperty.RegisterAttached( "DisabledImage", typeof(ImageSource), typeof(ImageLoader), new UIPropertyMetadata(null)); }
按钮样式
用法
... ...
您可以通过Image
样式实现此目的:
这是使用专门样式处理它的另一种方法。 应该指出的是,使用附加属性来正确定制图像文件可以进一步改善这一点。
Rectangle对于命中测试很重要,否则IsMouseOver不会触发。 并且ContentAlignment上的Stretch是必需的,否则按钮的ContentPresenter将不会跨越整个按钮,因此IsMouseOver不会再次触发。