繁体   English   中英

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

[英]Custom Controls: Add custom button click logic within a custom control

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

目前,我已经定义了一堆不同的控件,并在控件模板中硬编码了它们的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 */
    };
}

但我想知道我是否不能以更有条理的方式做到这一点。 我观看了有关路由事件以使用自定义ICommand教程,但不幸的是我无法使其在自定义控件中工作。 (直到mm8指出了一个方法)

您可以创建一个自定义类并向其添加依赖项属性 像这样的东西:

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}" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM