6

In WPF ComboBox does not have SelectedText property.

Is there a way to achieve the same functionality as TextBox SelectedText has in WPF

02Anant
  • 328
  • 1
  • 5
  • 13

6 Answers6

13

You can get access to the ComboBox's TextBox by using:

var edit = (TextBox)myCombo.Template.FindName("PART_EditableTextBox", myCombo);

Then you can access the SelectedText property of that TextBox:

var selectedText = edit.SelectedText;
codekaizen
  • 26,990
  • 7
  • 84
  • 140
  • 1
    This only works if your ComboBox is already shown (i.e. it is generated from its ControlTemplate), so you can't do something like create a ComboBox and focus on its TextBox immediately – hillin Apr 19 '16 at 10:04
1

Because WPF is "lookless" you can display your combobox items in any manner you wish. there may or may not be a text item.

MyCombo.SelectedText doesn't make any sense if you are, for example, display icons in there.

What you want is ComboBox.SelectedItem and then access your object. for example, if you are using a backing list of "People" objects.... MyComboBox.SelectedItem.PersonName

typically, the SelectedItem is databound to your object model or to another control.

Muad'Dib
  • 28,542
  • 5
  • 55
  • 68
  • I got the answer in the above Post. I need SelectedText from the ComboBox to process them further, When ComboBox is in Edit mode. – 02Anant Jul 02 '10 at 22:32
0

Use this:

ComboBoxItem Item = (ComboBoxItem) YourComboBoxName.SelectedValue;

Then this:

Console.WriteLine(Item.Content);
hichris123
  • 10,145
  • 15
  • 56
  • 70
J Garza
  • 131
  • 1
  • 2
0

Why Don't You Try :

string selectedtext= Combobox.Text;

It works for me.

0

Another approach:

(string)comboBox.SelectedItem.GetType().GetProperty(DisplayMemberPath).GetValue(comboBox.SelectedItem);
Tzwenni
  • 139
  • 3
  • 7
0

There is no property called the selectedText but you can achive that by ComboBox.SelectedValue.ToString() method. It's because the values of an combobox is by default of the type Object so we have to suitably typecast it.

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
  • 1
    The is not completely true. If you are using a custom item template, your code will not match the rendered string. Ideally, you should be so you can, for example, put Employee objects in the list instead of a bunch of custom generated strings. – Rich Jun 11 '12 at 20:24