WPF TextBox 一些設置技巧


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;
        }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM