Reputation: 8506
This should be really simple: I've got a ContentDialog with a TextBox. When the app is running on a tablet and the dialog is launched, I want the text within the TextBox selected and the on-screen (virtual) keyboard automatically shown. Sure, the default behavior of the user having to tap inside the TextBox will cause the keyboard to show, but that's one extra step for the user (and text selection is lost).
XAML:
<ContentDialog ... >
<Grid>
<TextBox Name="TbInput" Text="AAA" />
</Grid>
</ContentDialog>
Code-behind:
public MyDialog()
{
this.InitializeComponent();
this.Loaded += MyDialog_Loaded;
}
private async void MyDialog_Loaded(object sender, RoutedEventArgs e)
{
TbInput.SelectAll();
TbInput.Focus(FocusState.Programmatic);
}
Update
Just to clarify, the desired behavior is this: when running on a tablet or mobile, when the dialog opens, I want 1) all existing text in the TextBox to be selected and 2) and virtual keyboard is shown.
That way the user can immediately start typing in replacement text.
Update 2
I do wonder if I'm dealing with a bug or some Windows 10 setting: on this page it clearly states
By default, the onscreen touch keyboard is displayed whenever focus moves to an editable text box and the most recent input was generated by touch. This happens whether focus is set programmatically or by user interaction.
I can verify that my programatically-set focus is being successfully set to the TextBox (return value of Focus()
is true
), and the most recent input in my test scenarios is by touch.
Upvotes: 0
Views: 1545
Reputation: 32775
the TextBox will cause the keyboard to show, but that's one extra step for the user (and text selection is lost).
The problem is you have executed SelectAll
method, when you enter new text, the selected area is overwritten. So you need to move cursor to end of text.
private async void MyDialog_Loaded(object sender, RoutedEventArgs e)
{
TbInput.SelectionStart = TbInput.Text.Length;
TbInput.SelectionLength = 0;
TbInput.Focus(FocusState.Programmatic);
}
Update
For your requirement, you could set SelectionStart
to 0,SelectionLength
to TbInput.Text.Length
like follow.
private async void MyDialog_Loaded(object sender, RoutedEventArgs e)
{
TbInput.SelectionStart = 0;
TbInput.SelectionLength = TbInput.Text.Length;
TbInput.Focus(FocusState.Programmatic);
}
You could also use TextBox PlaceholderText to realize this. When you input new words, the PlaceholderText
will dismiss automatically.
<TextBox Name="TbInput" PlaceholderText="AAAAA" />
If you run it in the Tablet, the keyboard will not show automatically. You could use TryShow
method to show the keyboard.
private async void MyDialog_Loaded(object sender, RoutedEventArgs e)
{
TbInput.SelectionStart = 0;
TbInput.SelectionLength = TbInput.Text.Length;
TbInput.Focus(FocusState.Programmatic);
InputPane.GetForCurrentView().TryShow();
}
Upvotes: 4