1.弹窗回车键和Esc键绑定
(1)为TextBox设置TextChanged和KeyDown事件
(2)添加代码
在cs文件的构造函数中添加以下语句,使光标聚焦于TextBox
inputTextContent.Focus();
添加绑定回车键和Esc键的代码
//cs
private void inputTextContent_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
//将文本框中的内容赋值给vm中对应变量的内容
vm.InputText = inputTextContent.Text;
//键盘按下回车,调用vm中的确定方法
vm.ConfirmAction();
}
else if (e.Key == Key.Escape)
{
//键盘按下Esc,调用vm中的取消方法
vm.CancelAction();
}
}
//ViewModel
public void CancelAction()
{
RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel, null));
}
public void ConfirmAction()
{
var parameter = new DialogParameters();
parameter.Add("inputText", InputText);
RequestClose?.Invoke(new DialogResult(ButtonResult.OK, parameter));
}
2.打开弹窗TextBox光标到末端
添加设置光标位置的代码
private void inputTextContent_TextChanged(object sender, TextChangedEventArgs e)
{
//在TextBox有绑定的内容时,最好添加一个TextChange事件
//设置光标在文本的末端
int l = inputTextContent.Text.Length;
inputTextContent.SelectionStart = l;
}
其他情况
有些控件如Grid,默认无法聚焦,需要先设置成能聚焦再添加KeyDown事件。
<Grid x:Name="selectDialogGrid" KeyDown="selectDialogGrid_KeyDown" Focusable="True"/>
事件方法内容与以上相同。