c# - 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”。我将代码片段编辑为正确的。
解决方案
看起来这只是一个错字,我将您的代码放入示例项目中,它按预期工作。
public static readonly DependencyProperty MouseOverCommandProperty =
DependencyProperty.RegisterAttached("MouseOverCommand", typeof(ICommand), typeof(MouseMovement),
new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseOverCommandChanged)));
推荐阅读
- java - Apache POI 3.17 HSSF 不接受“IFERROR”
- reactjs - React lazy load won't work inside React perfect scroll bar
- c++ - Doubly Linked List with struct c++
- spring - Spring Boot 数据源配置
- javascript - Using jQuery to auto calculate amount
- python - How to reset a global variable and pass it to Decorator
- mysql - What is wrong with the following trigger before an update?
- vba - Can I select a group of tables to format in microsoft word using VBA?
- python - Unable to downgrade version of Python package by `pip install -I`
- r - r string cleaning , retain everything before the last underscore