【问题标题】:Subscribe to the Button's events into a custom control将Button的事件订阅到自定义控件中
【发布时间】:2010-04-30 14:19:17
【问题描述】:

你知道如何订阅我的 customControl 的基础事件吗? 我有一个带有一些依赖属性的自定义控件:

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 ) );
}

我想订阅 Button 的事件(如 MouseLeftButtonDown)以在我的 customControl 中运行一些代码。

你知道我怎样才能在构造函数中做这样的事情吗?

static MyCustomControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata( typeof( MyCustomControl ), new FrameworkPropertyMetadata( typeof( MyCustomControl ) ) );
        MouseLeftButtonDownEvent += (object sender, MouseButtonEventArgs e) => "something";
    }

感谢您的帮助

【问题讨论】:

    标签: c# wpf events custom-controls


    【解决方案1】:

    我找到了解决办法!

    你只需要重写OnMouseLeftButtonDown 方法。不要忘记在您的代码之后调用 base.OnMouseLeftButtonDown。

    【讨论】:

      【解决方案2】:

      嗯,这可以工作。如果您想摆脱 xaml 文件中的任何代码隐藏并希望遵守 MVVM,那么我建议您查看附加行为。

      这是一个链接:http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

      这是一个很好的资源,上周才救了我。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-27
        • 2012-01-27
        • 2023-03-28
        • 2012-01-08
        • 1970-01-01
        • 2011-09-06
        • 1970-01-01
        相关资源
        最近更新 更多