Reputation: 185
I have a ComboBox declared as follows:
<ComboBox Name="txtUserName" IsEditable="True" />
I want to select the ComboBox's text field on focus, but I can't figure out how to do this. Currently, when the ComboBox is focused on programmatically (through "txtUserName.Focus()"), it allows the user to scroll through the different items, but requires an additional click to highlight the text field.
Any thoughts?
Upvotes: 3
Views: 434
Reputation: 185
The solution I used was to add the following code to the window's loaded event:
var textBox = (txtUserName.Template.FindName("PART_EditableTextBox", txtUserName) as TextBox);
if (textBox != null)
{
textBox.Focus();
textBox.SelectionStart = textBox.Text.Length;
}
The solution came from one of the suggested answers here: How to add a focus to an editable ComboBox in WPF
Upvotes: 1
Reputation: 1347
Try add comboBox template like this:
<ComboBox Name="txtUserName" IsEditable="True">
<ComboBox.Template>
<ControlTemplate>
<TextBox Text="{Binding Path=/*your property*/}"/>
</ControlTemplate>
</ComboBox.Template>
</ComboBox>
Upvotes: 0
Reputation: 85
Try this:
if (txtUserName.Items.Count > 0)
{
txtUserName.SelectedIndex = 0;
}
Also, you may want to use a different prefix, like "cbo". Other readers of the code will assume it is a textbox, not a combobox.
Upvotes: 0