🚀
AvaloniaUIのTextBoxでCtrl+Enterを取得する方法
AvaloniaUIのTextBoxでmultilineの編集を有効にするためにTextBox.AcceptsReturnプロパティをtrueにすると、enter入力時にKeyDownイベントが発生しなくなる。この場合にCtrl+Enter入力時に何らかの処理を実装する。
使用環境
Windows 11 : Home 22H2 + Visual Studio Community 2022(64bit) Version 17.12.3
Avalonia 11.2.3
Ctrl+Enter入力時の動作
通常はKeyDownイベント内で以下のように処理すれば実装できる。
TextBox.KeyDown += (sender, e) =>
{
if (e.Key == Key.Enter && e.KeyModifiers == KeyModifiers.Control)
{
//何かの処理
}
};
しかし、多ライン編集を行うためにTextBoxのAcceptsReturnプロパティをtrueにすると、enter入力時にKeyDownイベントが発生しなくなりこの方法は使えない。
AcceptsReturn
Makes the input multi-line by allowing the user to enter line returns. A vertical scrollbar will appear if the content exceeds the height available.
実装方法
keybindingを使うと正常に処理できる
var keyBinding = new KeyBinding
{
Gesture = new KeyGesture(Key.Enter, KeyModifiers.Control), // Ctrl+Enter
Command = ReactiveCommand.Create(() =>
{
//何かの処理
}),
};
TextBox.KeyBindings.Add(keyBinding);
Discussion