What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

后端 未结 12 1530
囚心锁ツ
囚心锁ツ 2020-12-13 08:48

Goal: issue an event when items in a combobox drop down list is selected.

Problem: Using \"SelectionChanged\", however, if the user

12条回答
  •  囚心锁ツ
    2020-12-13 09:23

    I hope that you will find helpfull the following trick.

    You can bind both the events

    combobox.SelectionChanged += OnSelectionChanged;
    combobox.DropDownOpened += OnDropDownOpened;
    

    And force selected item to null inside the OnDropDownOpened

    private void OnDropDownOpened(object sender, EventArgs e)
    {
        combobox.SelectedItem = null;
    }
    

    And do what you need with the item inside the OnSelectionChanged. The OnSelectionChanged will be raised every time you will open the combobox, but you can check if SelectedItem is null inside the method and skip the command

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combobox.SelectedItem != null)
            {
               //Do something with the selected item
            }
        }
    

提交回复
热议问题