Editable WPF ComboBox SelectAll on click

I have how to select SelectAll text when I click on a TextBox; I want to do the same for editable combobox - din find something. My code for TextBox is

private void OnPreviewMouseDown(Object sender, MouseButtonEventArgs e) { txtBox.SelectAll(); txtBox.Focus(); e.Handled = true; } 

How can this be done for Editable Combobox?

Update Code for Combox that gives me the output I want:

 private void cboMouseDown(object sender, MouseButtonEventArgs e) { var textBox = (cbo.Template.FindName("PART_EditableTextBox", cbo) as TextBox); if (textBox != null) { textBox.SelectAll(); cbo.Focus(); e.Handled = true; } } 

But now the combobox doesn't work, any suggestion?

Update-2 : instead of PreviewMouseDown - I tried PreviewMouseUp, and now a popup menu appears; but when he once clicked on the box, and then tried to open the drop-down list, the window freezes. However, I did the work that I put in response. I would really appreciate your comments, though, if this is the right and safe decision I can go with.

+6
source share
3 answers

Use the GotFocus event and select text similar to this

  var comboTextBoxChild = comboBox.FindChild(typeof(TextBox), "PART_EditableTextBox") as TextBox; comboTextBoxChild .SelectAll(); 

Here combobox is your editable name Combobox

+5
source

The possible solution that I have, and its work for me, needs some suggestion, although if this is normal or not; I am using the PreviewMouseUp event for a ComboBox:

 private void cboMouseUp(object sender, MouseButtonEventArgs e) { var textBox = (cbo.Template.FindName("PART_EditableTextBox", cbo) as TextBox); if (textBox != null && !cbo.IsDropDownOpen) { Application.Current.Dispatcher.BeginInvoke(new Action(()=>{ textBox.SelectAll(); textBox.Focus(); //e.Handled = true; })); } 
+3
source

I'm a little late to the party, but I had the same problem lately, and after testing several solutions I came up with my own (for this purpose I created a special control):

 public class ComboBoxAutoSelect : ComboBox { private TextBoxBase textBox; public override void OnApplyTemplate() { base.OnApplyTemplate(); textBox = GetTemplateChild("PART_EditableTextBox") as TextBoxBase; } protected override void OnPreviewGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { // if event is called from ComboBox itself and not from any of underlying controls // and if textBox is defined in control template if (e.OriginalSource == e.Source && textBox != null) { textBox.Focus(); textBox.SelectAll(); e.Handled = true; } else { base.OnPreviewGotKeyboardFocus(e); } } } 

you can do the same with events, but you will need to search for "PART_EditableTextBox" every time, and here we do it only once to change the template

+1
source

Source: https://habr.com/ru/post/988969/


All Articles