Subscribe to Button events in your custom control
Do you know how I can subscribe to my customControl's base event? I have a custom control with some dependency properties:
public class MyCustomControl : Button
{
static MyCustomControl ()
{
DefaultStyleKeyProperty.OverrideMetadata( typeof( MyCustomControl ), new FrameworkPropertyMetadata( typeof( MyCustomControl ) ) );
}
public ICommand KeyDownCommand
{
get { return (ICommand)GetValue( KeyDownCommandProperty ); }
set { SetValue( KeyDownCommandProperty, value ); }
}
public static readonly DependencyProperty KeyDownCommandProperty =
DependencyProperty.Register( "KeyDownCommand", typeof( ICommand ), typeof( MyCustomControl ) );
public ICommand KeyUpCommand
{
get { return (ICommand)GetValue( KeyUpCommandProperty ); }
set { SetValue( KeyUpCommandProperty, value ); }
}
public static readonly DependencyProperty KeyUpCommandProperty =
DependencyProperty.Register( "KeyUpCommand", typeof( ICommand ), typeof( MyCustomControl ) );
public ICommand KeyPressedCommand
{
get { return (ICommand)GetValue( KeyPressedCommandProperty ); }
set { SetValue( KeyPressedCommandProperty, value ); }
}
public static readonly DependencyProperty KeyPressedCommandProperty =
DependencyProperty.Register( "KeyPressedCommand", typeof( ICommand ), typeof( MyCustomControl ) );
}
And I want to subscribe to Button events (like MouseLeftButtonDown) to run some code in my customControl.
Do you know how I can do something like this in the constructor?
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata( typeof( MyCustomControl ), new FrameworkPropertyMetadata( typeof( MyCustomControl ) ) );
MouseLeftButtonDownEvent += (object sender, MouseButtonEventArgs e) => "something";
}
thanks for the help
+2
a source to share
2 answers
I found a solution!
You just need to override the OnMouseLeftButtonDown method . Remember to call base.OnMouseLeftButtonDown after your code.
+2
a source to share
Well, it might work. If you want to be free of the code in your xaml file and would like to obey MVVM, I would suggest you look at the Attached Actions.
Here is the link: http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx
This is a very good resource and only saved me last week.
+1
a source to share