TextChanged event handler in a WPF ComboBox

Looking to the WPF, I can see the event TextChanged has disappeared from the combo boxes. I am surprised, because I found it really useful for the editable Combo Boxes (IsEditable ="True").

So as I needed it for my personal purposes I decided to create a custom combo control inherited from the base one that has that event.

First of all I create a custom class, and I make it Inherit from combobox:



Now, the approach is create a TextBox control, that has the TextChanged event, and bind it to the ComboBox. As this is a class, we won't be able to do it via XAML.
Programmatically, it is something like this:

Instead iterating for each row setting a default value like this

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;

namespace WpfApplication1
{
internal class CustomComboBox : System.Windows.Controls.ComboBox
{
//Define the TextChangedEventHandler
public event TextChangedEventHandler TextChanged;

//Have a texbox to handle the textchanged event of the combo
TextBox tb2;

///
/// On EndInit the control is fully loaded
///

public override void EndInit()
{
//Call the base method
base.EndInit();
//Create the texbox it is going to be linket to our combobox
tb2 = new TextBox();
//And bind the text of the texbox...
Binding b = new Binding("Text");
//To the text of the combo
b.Source = this;
//Set the bind
BindingOperations.SetBinding(tb2, TextBox.TextProperty, b);
//And handle the textchanged event of the textbox.
//There we will raise the textchanged event of the combobox
tb2.TextChanged += new TextChangedEventHandler(tb2_TextChanged);

}

void tb2_TextChanged(object sender, TextChangedEventArgs e)
{
//Just raise the textChanged Event of the combo if something it is
//subscribed to our event
if (TextChanged != null)
{
TextChanged(sender, e);
}
}
}
}

0 comments:

Post a Comment