自定义控件:在自定义控件中添加自定义按钮点击逻辑

问题描述

我正在创建一个屏幕键盘自定义控件,该控件将文本发送到目标TextBox。在此键盘内部,我将布置自定义KeyboardKey按钮控件,这些控件具有关联的文本输出键盘按键(Backspace,箭头键等)。

目前,我已经定义了许多不同的控件,并将它们的Click功能硬编码在控件模板中:

public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    Click += (s,e) =>
    {
        keyboard.Target.Focus(); // Focus on parent keyboard's TextBox
        /* Key press logic,e.g. send character output or execute key press */
    };
}

但是我想知道是否无法以一种更有条理的方式做到这一点。我看着this tutorial about routed events自定义ICommand一起使用,但是很遗憾,我无法使其在自定义控件中运行。 (直到mm8都指出了一种解决方法

解决方法

您可以创建一个自定义类,然后向其中添加dependency properties。像这样:

public class CustomButton : Button
{
    public static readonly DependencyProperty SomeCommandProperty = 
        DependencyProperty.Register(nameof(SomeCommand),typeof(ICommand),typeof(CustomButton));

    public ICommand SomeCommand
    {
        get { return (ICommand)GetValue(SomeCommandProperty); }
        set { SetValue(SomeCommandProperty,value); }
    }

    protected override void OnClick()
    {
        base.OnClick();
        //do something based on the property value...
        if (SomeCommand != null)
            SomeCommand.Execute(null);
    }
}

然后您可以在使用控件的任何地方设置依赖项属性,例如:

<local:CustomButton Command="{Binding SomeCommand}" />