[WPF]设置控件的输入光标移(Passwordbox、TextBox)

语言类型:c#;

项目类型:WPF;

实现如下:

一、TextBox

textBox.SelectionStart = position;

二、PasswordBox

passwordBox.GetType()
    .GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic)
    .Invoke(passwordBox, new object[] { position, 0 });

三、处理过的代码


        #region Functions.Controls.Textbox

        /// 
        /// Void:设置输入光标的位置
        /// 
        /// 文本框
        /// 设置的光标位置(等于-1与大于max为最后位置)
        public static void SetCursor(TextBox tBox, int position)
        {
            switch (position)
            {
                case -1: { position = tBox.Text.Length; } break;
                default:
                    {
                        if (position < 0) { return; }
                        else
                        {
                            var _maxLength = tBox.Text.Length;
                            if (position > _maxLength) { position = _maxLength; }
                        }
                    }
                    break;
            }

            tBox.SelectionStart = position;
        }

        #endregion

        #region Functions.Controls.PasswordBox

        /// 
        /// Void:设置输入光标的位置
        /// 
        /// 密码框
        /// 设置的光标位置(等于-1与大于max为最后位置)
        public static void SetCursor(PasswordBox pBox, int position = -1)
        {
            switch (position)
            {
                case -1: { position = pBox.Password.Length; } break;
                default:
                    {
                        if (position < 0) { return; }
                        else
                        {
                            var _maxLength = pBox.Password.Length;
                            if (position > _maxLength) { position = _maxLength; }
                        }
                    }
                    break;
            }

            pBox.GetType()
                .GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic)
                .Invoke(pBox, new object[] { position, 0 });
        }

        #endregion

 

 

 

 

 

你可能感兴趣的:(C#,WPF)