I am creating an on-screen keyboard Custom Control that sends text to a target TextBox
. Inside this keyboard, I am laying out custom KeyboardKey
button controls that have an associated text output or keyboard keypress (Backspace, Arrow Keys, etc.).
Currently, I have defined a bunch of different controls and hard-coded their Click
functionality inside of the control template:
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 */
};
}
But I was wondering if I couldn't do it in a more organised way. I watched this tutorial about routed events to work with custom ICommand
s but unfortunately I couldn't make it work in a custom control. (Until mm8
pointed out a way to do it after all)
You could create a custom class and add dependency properties to it. Something like this:
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);
}
}
You could then set the dependency properties everywhere where you use the control, eg:
<local:CustomButton Command="{Binding SomeCommand}" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.