tags:

views:

44

answers:

1

I have a WPF combobox and a button as given below

<ComboBox Name="cmbExpressions" IsEditable="True"/>
<Button x:Name="btnSubmit" Content="Apply Selected" Click="btnSubmit_Click"/>

Now, I have written some text in the combobox at runtime say

stackoverflow,sometext,someothertext.

After that by using mouse, say I have highlighted "sometext".

Now I clicked on the Submit button and I am expecting to get the

output as only the 

selected /highlighted text  of the combobox which is "Sometext" here

.

I have tried a lot with selected item, text etc. but nothing worked.

How can I achieve this.

I am using C# 3.0 & WPF

Thanks

+3  A: 

The ComboBox doesn't track the text selection itself, so if you want to get the selected text you'll need to find the TextBox in the template for the ComboBox and read the selection information from there. Keep in mind that it may not have one if the control has been re-templated. It would look something like this:

var editableTextBox = cmbExpressions.Template.FindName("PART_EditableTextBox", cmbExpressions) as TextBox;
if (editableTextBox != null)
{
    var text = editableTextBox.SelectedText;
}

That sounds like a very strange UI, though. Users typically don't expect the text selection of a combo box to affect behavior. Be aware that the ComboBox will automatically select all the text in the TextBox when it gets focus.

Quartermeister
The ComboBox class has a TemplatePartAttribute: `[TemplatePartAttribute(Name = "PART_EditableTextBox", Type = typeof(TextBox))]`. This tells you the control template expects a part with that name and that type.
Quartermeister