c# - 将按钮的事件订阅到自定义控件中

标签 c# wpf events custom-controls

你知道我如何订阅我的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)以在我的自定义控件中运行一些代码。

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

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

谢谢你的帮助

最佳答案

我找到了解决方案!

您只需覆盖 OnMouseLeftButtonDown方法。不要忘记在代码后调用 base.OnMouseLeftButtonDown。

关于c# - 将按钮的事件订阅到自定义控件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2745089/

相关文章:

c# - 如何使用 App.config 连接 C# 和 Db?

WPF WebBrowser - 如何缩放内容?

c# - 当我的任何 UI 元素在 WPF/C# 中发生更改时,是否会触发任何事件?

WPF与窗口的RelativeSource绑定(bind)需要路径中的 "DataContext"?

java - Apache wicket - DropDownChioce.onSelectionChanged() 不起作用

javascript - 关于输入问题的文本区域

c# - 检查 DataRow 是否包含特定列的最佳实践

c# - 一次运行所有测试会导致其中一些测试失败,但是当它们被单独触发时,它们就可以正常工作

c# - 如何在 C# 中将复选框颜色更改为深灰色(禁用)?

c# - Wpf动画背景颜色