3

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?

mastur cheef
  • 185
  • 1
  • 3
  • 15
  • 2
    That\`s probably how ComboBox handles focus by default. If you want to change this, you\`ll have to go deeper. There are some similar questions, they might be useful: [question one](http://stackoverflow.com/questions/2963462/how-to-add-a-focus-to-an-editable-combobox-in-wpf), [question two](http://stackoverflow.com/questions/2151285/wpf-selecting-all-the-text-in-and-setting-focus-to-a-comboboxs-editable-textbo). – icebat Nov 01 '13 at 14:29
  • What do you mean? When I use the arrow to scroll it highlights. – paparazzo Nov 01 '13 at 14:47
  • Found the solution in your first link @icebat – mastur cheef Nov 01 '13 at 14:58

3 Answers3

1

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

Community
  • 1
  • 1
mastur cheef
  • 185
  • 1
  • 3
  • 15
0

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.

0

Try add comboBox template like this:

<ComboBox Name="txtUserName" IsEditable="True">
        <ComboBox.Template>
          <ControlTemplate>
              <TextBox Text="{Binding Path=/*your property*/}"/>
           </ControlTemplate>
         </ComboBox.Template>
 </ComboBox>
Aleksey
  • 1,299
  • 9
  • 13