ICommand 类型的附加 WPF 属性

WPF Attached Property of type ICommand

我想为按钮实现一个新的附加 属性,如果鼠标悬停则注册,如果悬停则执行命令。 这是 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);
        }
}

和xaml:

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

每次我尝试 运行 时,我都会收到错误消息:“无法为按钮类型的 属性“SetMouseOverCommand”指定绑定。只能为依赖项指定绑定[= DependencyObject 的 34=]

说到这里我有点卡住了,也许你有一些想法。

编辑:如已接受的答案中所述,错误是错字。 Attached属性 名称被设置为“MouveOverCommand”而不是“MouseOverCommand”。我编辑了代码片段以使其正确。

看起来只是一个打字错误,我将您的代码放入示例项目中并且按预期运行。

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