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



我正在创建一个屏幕键盘自定义控件,用于向目标TextBox发送文本。在这个键盘里,我正在布置自定义的KeyboardKey按钮控件,这些控件具有相关的文本输出或键盘按键(Backspace、Arrow Keys等(

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

最新更新