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

后端 未结 12 1585
囚心锁ツ
囚心锁ツ 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条回答
  •  旧时难觅i
    2020-12-13 09:25

    This problem bugs me for a long time since none of the work-around worked for me :(

    But good news is, the following method works fine for my application.

    The basic idea is to register a EventManager in App.xmal.cs to sniff PreviewMouseLeftButtonDownEvent for all ComboBoxItem, then trigger the SelectionChangedEvent if the selecting item is the same as the selected item, i.e. the selection is performed without changing index.

    In App.xmal.cs:

    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            // raise selection change event even when there's no change in index
            EventManager.RegisterClassHandler(typeof(ComboBoxItem), UIElement.PreviewMouseLeftButtonDownEvent,
                                              new MouseButtonEventHandler(ComboBoxSelfSelection), true);
    
            base.OnStartup(e);
        }
    
        private static void ComboBoxSelfSelection(object sender, MouseButtonEventArgs e)
        {
            var item = sender as ComboBoxItem;
    
            if (item == null) return;
    
            // find the combobox where the item resides
            var comboBox = ItemsControl.ItemsControlFromItemContainer(item) as ComboBox;
    
            if (comboBox == null) return;
    
            // fire SelectionChangedEvent if two value are the same
            if ((string)comboBox.SelectedValue == (string)item.Content)
            {
                comboBox.IsDropDownOpen = false;
                comboBox.RaiseEvent(new SelectionChangedEventArgs(Selector.SelectionChangedEvent, new ListItem(), new ListItem()));
            }
        }
    }
    

    Then, for all combo boxes, register SelectionChangedEvent in a normal way:

    
    

    Now, if two indices are different, nothing special but the ordinary event handling process; if two indices are the same, the Mouse Event on the item will first be handled, and thus trigger the SelectionChangedEvent. In this way, both situations will trigger SelectionChangedEvent :)

提交回复
热议问题