简体   繁体   English

ICommand 类型的 WPF 附加属性

[英]WPF Attached Property of type ICommand

I want to implement a new Attached Property for buttons which registers if the mouse is over and executes a Command if so.我想为按钮实现一个新的附加属性,如果鼠标悬停,则注册并执行命令。 This is the C# code:这是 C# 代码:

 public class MouseMovement { public static readonly DependencyProperty MouseOverCommandProperty = DependencyProperty.RegisterAttached("MouseOverCommand", typeof(ICommand), typeof(MouseMovement), new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseOverCommandChanged))); private static void MouseOverCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { FrameworkElement element = (FrameworkElement)d; element.MouseEnter += new MouseEventHandler(element_MouseOver); } private static void element_MouseOver(object sender, MouseEventArgs e) { FrameworkElement element = (FrameworkElement)sender; ICommand cmd = GetMouseOverCommand(element); cmd.Execute(e); } public static void SetMouseOverCommand(UIElement element, ICommand value) { element.SetValue(MouseOverCommandProperty, value); } private static ICommand GetMouseOverCommand(FrameworkElement element) { return (ICommand)element.GetValue(MouseOverCommandProperty); } }

And the xaml:和xaml:

 <Button mouseEvents:MouseMovement.MouseOverCommand="{Binding ButtonMouseOverCommand}" Grid.Row="0" Background="Transparent" BorderThickness="0" > <StackPanel> <Image /> <TextBlock Text="BL-Invoices" Foreground="White"/> </StackPanel> </Button>

Everytime I try to run this I get the error: "Binding can not be specified for the property "SetMouseOverCommand" of type button. Binding can only be specified for a DependencyProperty of a DependencyObject"每次我尝试运行它时,我都会收到错误消息:“无法为按钮类型的属性“SetMouseOverCommand”指定绑定。只能为 DependencyObject 的 DependencyProperty 指定绑定”

I got a little bit stuck at this point, maybe you have some ideas.我在这一点上有点卡住了,也许你有一些想法。

Edit: As stated in the accepted answer the mistake was a typo.编辑:如接受的答案所述,该错误是一个错字。 The AttachedProperty name was set to "MouveOverCommand" instead of "MouseOverCommand". AttachedProperty 名称设置为“MouveOverCommand”而不是“MouseOverCommand”。 I edited the code snippet to be correct.我编辑了代码片段以使其正确。

It looks like it's just a typo, I put your code into a sample project and it worked as expected.看起来这只是一个错字,我将您的代码放入示例项目中,并且按预期工作。

public static readonly DependencyProperty MouseOverCommandProperty =
        DependencyProperty.RegisterAttached("MouseOverCommand", typeof(ICommand), typeof(MouseMovement), 
            new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseOverCommandChanged)));

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

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