开发者

Subscribe to the Button's events into a custom control

开发者 https://www.devze.com 2022-12-29 05:48 出处:网络
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 :

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 Dep开发者_开发问答endencyProperty 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


I found the solution !

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号