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:
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);
}
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
And the xaml:
<Button mouseEvents:MouseMovement.MouseOverCommand="{Binding ButtonMouseOverCommand}" Grid.Row="0" Background="Transparent" BorderThickness="0" >
<StackPanel>
<Image />
<TextBlock Text="BL-Invoices" Foreground="White"/>
</StackPanel>
</Button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
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"
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". I edited the code snippet to be correct.
CodePudding user response:
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)));