首页 > 解决方案 > ICommand 类型的 WPF 附加属性

问题描述

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

在这一点上我有点卡住了,也许你有一些想法。

编辑:正如接受的答案中所述,错误是一个错字。AttachedProperty 名称设置为“MouveOverCommand”而不是“MouseOverCommand”。我将代码片段编辑为正确的。

标签: c#wpfxamlattached-properties

解决方案


看起来这只是一个错字,我将您的代码放入示例项目中,它按预期工作。

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

推荐阅读