Home > WPF > Getting the text of the selecteditem in Combobox

Getting the text of the selecteditem in Combobox

February 26, 2008 lee Leave a comment Go to comments

When you look at the Text property in the SelectionChanged event of the ComboBox it returns the prior value
here is a way to get the right value (cb1 is the name of the ComboBox)

Add this in Window loaded event

DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox));

dpd.AddValueChanged(cb1, OnTextChanged);
 

and here is the handler

private void OnTextChanged(object sender, EventArgs args)
        {
            MessageBox.Show(cb1.Text);
        }

Categories: WPF
  1. michael
    February 26, 2008 at 5:45 pm | #1

    So, I did this in VB:

    Dim dpd As DependencyPropertyDescriptor

    dpd = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, GetType(ComboBox))

    dpd.AddValueChanged(cb1, AddressOf OnTextChanged)

    And then:

    Private Sub OnTextChanged(ByVal sender As Object, ByVal args As EventArgs)

    End Sub

    This works fine in VB. But, WHY would they do such a thing!!

  2. leeintech
    February 26, 2008 at 6:15 pm | #2

    The selectedItem is set but the template might not be applied when the event is fired

  3. Jen
    March 16, 2008 at 9:16 am | #3

    No dependency property is necessary for getting the text. this code worked for me:

    private void ComboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
    string currentText = ComboBox1.SelectedValue as string;
    }

  4. lee
    March 16, 2008 at 10:48 am | #4

    if the displaymemberpath and selectedvaluepath are same then the value and display text will be the same and your code will work

  5. November 24, 2008 at 10:31 pm | #5

    i am having trouble firing off the selectionchanged event for a combobox in WPF using VB.Net 2008. The event doesn’t fire off.

  6. lee
    November 25, 2008 at 9:38 am | #6

    make sure there are no duplicate items

  1. No trackbacks yet.