Hello,
there is a known bug with the WPF PasswordBox and touch devices (does not pop up virtual keyboard).
So I made an own usercontrol.
It has a PasswordBox and a TextBox, both on same position, TextBox has Opacity 0.
When the textbox gets the focus, it pops up the virtual keyboard, then gives to focus to the PasswordBox:
private void Text_GotFocus(object sender, System.Windows.RoutedEventArgs e)
{
CustomPasswordBox.Focus();
SetSelection(CustomPasswordBox, currentCaretIndex, 0);
}
That is working perfect.
The textbox gets all input events from the mouse.
So I need to set the cursor position, selection etc. manually.
I found one problem with this, I have no idea why.
private int currentCaretIndex = 0;
This currentCaretIndex should save my cursor position.
The following code should set the selection to my CustomPasswordBox,
when using mouse on the CustomTextBox.
But it is not working, when I try to click behind the last character,
it is one position before the last character. When adding +1 to it,
I cannot click left of the first character anymore.
It seems CustomTextBox.GetCharacterIndexFromPoint is returning wrong values somehow in that cases. Any idea to fix that? Thanks a lot!
private void SetSelection(PasswordBox passwordBox, int start, int length)
{
if (start >= 0 && length <= passwordBox.Password.Length)
{
passwordBox.GetType().GetMethod("Select", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(passwordBox, new object[] { start, length });
}
}
private int CalculatePosition(Point mousePoint)
{
CustomTextBox.Text = "";
for (int i = 0; i < CustomPasswordBox.Password.Length; i++)
{
CustomTextBox.Text += CustomPasswordBox.PasswordChar;
}
return CustomTextBox.GetCharacterIndexFromPoint(mousePoint, true);
}
private void CustomTextBox_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
Point mousePos = new Point(e.GetPosition(CustomTextBox).X, e.GetPosition(CustomTextBox).Y);
currentCaretIndex = CalculatePosition(mousePos);
selectionStart = currentCaretIndex;
isMouseDown = true;
}
private void CustomTextBox_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (!isMouseDown)
{
return;
}
Point mousePos = new Point(e.GetPosition(CustomTextBox).X, e.GetPosition(CustomTextBox).Y);
selectionEnd = CalculatePosition(mousePos);
SetSelection(CustomPasswordBox, System.Math.Min(selectionStart, selectionEnd), System.Math.Max(selectionStart, selectionEnd));
}
private void CustomTextBox_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
isMouseDown = false;
}