WPF TextBox 一些设置技巧

该博客介绍了 WPF TextBox 的一些设置技巧,运行环境为 Win10 x64、NetFrameWork 4.8。具体技巧包括取消输入法、将输入方式设定为 Overwrite 以及限定输入字符数,如在 KeyDown 事件里利用 SelectionStart 限定为 2 个字符。

WPF TextBox 一些设置技巧

运行环境:Win10 x64, NetFrameWork 4.8, 作者:乌龙哈里,日期:2019-05-01

参考:

章节:

  1. 取消输入法
  2. 输入方式设定为Overwrite
  3. 限定输入字符数

一、取消输入法

TextBox txbx=new TextBox();
InputMethod.SetIsInputMethodEnabled(txbx, false);//关掉输入法

二、输入方式设定为Overwrite

//把输入改成 overwrite 模式
// fetch TextEditor from myTextBox
TextBox txbx=new TextBox();
PropertyInfo textEditorProperty = typeof(TextBox).GetProperty("TextEditor", BindingFlags.NonPublic | BindingFlags.Instance);
object textEditor = textEditorProperty.GetValue(txbx, null);
// set _OvertypeMode on the TextEditor
PropertyInfo overtypeModeProperty = textEditor.GetType().GetProperty("_OvertypeMode", BindingFlags.NonPublic | BindingFlags.Instance);
overtypeModeProperty.SetValue(textEditor, true, null);

三、限定输入字符数

在 KeyDown 事件里利用 SelectionStart 来设定,下面例子是限定2个字符

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
        TextBox txbx = sender as TextBox;
        //只能有两个字符
        if (txbx.SelectionStart < 2)
        {
            e.Handled = false;//false才能通过
        }
        else
        {
            e.Handled = true;
        }
}

转载于:https://www.cnblogs.com/leemano/p/10799542.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值