1

I would like to know how to trigger the selectionChange event of a combobox only when the user himself change the selection of the list. (Avoid other cases) I found a solution here but I have some errors. Could you help me?

https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectionchangecommitted(v=vs.110).aspx

I added System.Windows.Forms in my .cs file and it says there is an ambiguity beetween 'System.Windows.Controls.ComboBox' and 'System.Windows.Forms.ComboBox' with the first line of the code below.

I dont know how to cast my sender into a comboBox.

ComboBox senderComboBox = (ComboBox)sender;

        if (senderComboBox.SelectionLength > 0)
        {
            //code here
        }

Thanks for help!

2 Answers2

0

You are trying to reference WinForms ComboBox and not WPF ComboBox. You can listen to SelectionChanged event of the control to know when user changes the selection.

A sample code from dotnetperls

XAML

<ComboBox
    HorizontalAlignment="Left"
    Margin="10,10,0,0"
    VerticalAlignment="Top"
    Width="120"
    Loaded="ComboBox_Loaded"
    SelectionChanged="ComboBox_SelectionChanged"/>

CS File

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // ... Get the ComboBox.
    var comboBox = sender as ComboBox;

    // ... Set SelectedItem as Window Title.
    string value = comboBox.SelectedItem as string;
    this.Title = "Selected: " + value;
}
123 456 789 0
  • 10,565
  • 4
  • 43
  • 72
  • My interpretation of the question is that he wants to know explicitly when a user has changed the value - as opposed to when it has been changed programmatically at runtime. – Adrian K May 18 '17 at 00:52
  • @AdrianK The issue he is raising is due to the fact that he referenced a ComboBox from Winforms and not WPF. If the user explicitly changed the value then that should trigger an event for SelectionChanged. It doesn't matter if it's changed at programatically runtime or user did it. – 123 456 789 0 May 22 '17 at 06:57
0

This sort of approach worked for me - XAML ComboBox SelectionChanged Fires OnLoad

Basically only wire-up the ComboBox_SelectionChanged event after the form has loaded - this will get you around the programmatic change that will fire onload. Beyond that I'm not sure. It might be that you need to use a different event, but I haven't looked into this.

Community
  • 1
  • 1
Adrian K
  • 9,880
  • 3
  • 33
  • 59