简体   繁体   English

我的ComboBox SelectionChangedEvent发送先前选择的项目

[英]My ComboBox SelectionChangedEvent sends the previously selected Item

So, whenever I change the selections I need to call a method, that compares the new selection with different options. 因此,每当我更改选择时,都需要调用一个方法,该方法会将新选择与不同选项进行比较。 Problem is, that it always sends the object selected before that 问题是,它总是发送在此之前选择的对象

Initially I thought I could just invert the selection, but that would only work with 2 options. 最初我以为我可以反转选择,但这仅适用于2个选项。

// Create the Combobox
ComboBox selectType = new ComboBox();
selectType.Text = "Select Type";
selectType.SelectionChanged += CallChange;

ComboBoxItem sortingAlgorithm = new ComboBoxItem();
sortingAlgorithm.Content = "Sorting Algorithm";

ComboBoxItem searchingAlgorithm = new ComboBoxItem();
searchingAlgorithm.Content = "Searching Algorithm";

// add the items to ComboBox

// Call on new selection
void CallChange(object sender, SelectionChangedEventArgs args)
{
   _controller.ChangeType((string)selectType.SelectionBoxItem);
}

I'd think that it just sends the new selection. 我认为它只是发送新的选择。 Do I have any thinking mistakes or did I mix anything up? 我是否有任何思维上的错误,或者我有没有混淆? Also I know that using Strings to compare selections is very bad practice, I am currently changing it all to dictionaries 我也知道使用字符串比较选择是非常不好的做法,我目前正在将其全部更改为字典

The selected item is only propagated after the changed event was handled. 所选项目仅在处理更改的事件之后传播。 This allows to manipulate the selected value before it is visible as selected. 这允许在所选值可见之前对其进行操作。 Therefore the moment the SelectionChanged event occurred, the SelectionBoxItem hasn't changed yet. 因此,在发生SelectionChanged事件时, SelectionBoxItem尚未更改。 You have to reference the selected item from the args object instead: 您必须改为引用args对象中的所选项目:

// Call on new selection
void CallChange(object sender, SelectionChangedEventArgs args)
{
  _controller.ChangeType(args.AddedItems.OfType<string>().FirstOrDefault() ?? string.Empty);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM