【WPF】弹窗回车键和Esc键绑定 打开弹窗TextBox光标到末端

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

事件方法内容与以上相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值