What you want to see on DotNetFunda.com ?
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 5579 |  Welcome, Guest!   Register  Login
 Home > Blogs > WPF > Get Selected/Highlighted Text from WPF ComboBox ...
Niladri.Biswas

Get Selected/Highlighted Text from WPF ComboBox

 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:


Experience:6 year(s)
Home page:http://www.dotnetfunda.com
Member since:Monday, October 25, 2010
Level:Diamond
Status: [Member]
Biography:Lead Engineer at HCL Technologies Ltd., having 6 years of experience in IT field.
I love to explore new technologies and love challenges and try to help others as much as possible not only by coding but also by all possible means.
>> Write Response - Respond to this post and get points

More Blogs

About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/26/2013 12:38:52 AM