我想為按鈕實作一個新的附加屬性,如果滑鼠懸停,則注冊并執行命令。這是 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”。我編輯了代碼片段以使其正確。
uj5u.com熱心網友回復:
看起來這只是一個錯字,我將您的代碼放入示例專案中,并且按預期作業。
public static readonly DependencyProperty MouseOverCommandProperty =
DependencyProperty.RegisterAttached("MouseOverCommand", typeof(ICommand), typeof(MouseMovement),
new FrameworkPropertyMetadata(new PropertyChangedCallback(MouseOverCommandChanged)));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357931.html
