views:

46

answers:

2

Do you know how can I subscribe to an event of the base of my customControl ? I've 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 whant to subscribe to Button's events (like MouseLeftButtonDown) to run some code in my customControl.

Do you know how can I 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 you help

+1  A: 

I found the solution !

You just have to override OnMouseLeftButtonDown method. Don't forget to call base.OnMouseLeftButtonDown after your code.

ThitoO
A: 

Well, that could work. If you wanted to be free of any code-behind in your xaml file and wanted to comply with MVVM, then I would have suggested you look into Attached Behaviors.

Here is a link: http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

It's a very good resource and saved me just last week.

Chris Leyva
Thank you Chris :)
ThitoO