1.WPF的TextBox文本框获取焦点后光标位置可以通过动态改变SelectionStart属性来设置,但是PasswordBox没有这个属性,怎么控制呢?
2.WPF的PasswordBox如果有值,在获取焦点的时候,焦点默认是在最前面,像下图这样:
3.如何可以做到获取焦点光标在最后面或者密码全选呢?
直接上代码:
1 private void PasswordPb_GotFocus(object sender, RoutedEventArgs e) 2 { 3 //SetSelection(PasswordPb, 0, 0);//焦点置于最前 4 SetSelection(PasswordPb, PasswordPb.Password.Length, 0);//焦点置于最后 5 //SetSelection(PasswordPb, 0, PasswordPb.Password.Length);//选中全部密码 6 } 7 8 private void SetSelection(PasswordBox passwordBox, int start, int length) 9 { 10 passwordBox.GetType() 11 .GetMethod("Select", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic) 12 .Invoke(passwordBox, new object[] { start, length }); 13 }
光标在最后面效果如下:
密码全选效果如下: