Blog author:
Niladri.Biswas | Posted on: 4/30/2012 | Category:
WPF Blogs | Views: 1317 | Status:
[Member] |
Points: 75
|
Alert Moderator
Download source file
Hi, in a recent requirement of mine, I had to choose only the text that has been highlighted/selected in a WPF combo box which is editable.
e.g.
Let us say we have a WPF combobox and a button as given below
<ComboBox Name="comboBox1" IsEditable="True" />
<Button Content="Get Selected Text" Name="button1" Click="button1_Click" />
Now, we have written some text in the combobox at runtime say
DLF/ILP 2012 is rocking at it's best.
After that by using mouse/keyboard, say we have highlighted "rocking".
Now when we click the button the result will be "rocking".
For doing so, I have written the below code
private void button1_Click(object sender, RoutedEventArgs e)
{
string result = string.Empty;
var editableTextBox = comboBox1.Template.FindName("PART_EditableTextBox", comboBox1) as TextBox;
if (editableTextBox != null)
{
result = editableTextBox.SelectedText;
}
MessageBox.Show(string.Format("Selected Text is {0}",result));
}
Code Explanation
The ComboBox doesn't track the text selection itself, so if we want to get the selected text we will need to find the TextBox in the template for
the ComboBox and read the selection information from there.The ComboBox class has a
TemplatePartAttribute:[TemplatePartAttribute(Name = "PART_EditableTextBox", Type = typeof(TextBox))].
This specifies the control template expects a part with that name and that type.
Hope this will be helpful.
Best Regards,
Niladri Biswas
Found interesting? Add this to: