gpt4 book ai didi

c# - 在不触发 SelectionChanged 事件的情况下设置 Combobox 的选定值

转载 作者:行者123 更新时间:2023-11-30 13:22:28 25 4
gpt4 key购买 nike

我有一个组合框:

<ComboBox Name="drpRoute" SelectionChanged="drpRoute_SelectionChanged" />

然后我在代码隐藏文件中设置列表项:

public ClientReports()
{
InitializeComponent();
drpRoute.AddSelect(...listofcomboxitemshere....)
}


public static class ControlHelpers
{
public static ComboBox AddSelect(this ComboBox comboBox, IList<ComboBoxItem> source)
{
source.Insert(0, new ComboBoxItem { Content = " - select - "});

comboBox.ItemsSource = source;
comboBox.SelectedIndex = 0;

return comboBox;
}
}

出于某种原因,当我设置 SelectedIndex 时,SelectionChanged 事件被触发。

到底如何设置 ItemSource 并设置 SelectedIndex 而不触发 SelectionChanged 事件?

我是 WPF 的新手,但它应该没有看起来那么复杂吧?还是我在这里遗漏了什么?

最佳答案

SelectionChanged 事件将触发,无论它是通过代码还是通过用户交互设置的。要解决此问题,您需要按照@Viv 建议在代码中更改处理程序时删除处理程序,或者在代码中更改它时添加一个标志以忽略更改。第一个选项不会触发事件,因为您没有监听它;在第二个选项中,您需要检查标志以查看它是否由代码更改触发。

更新:下面是使用标志的示例:

bool codeTriggered = false;

// Where ever you set your selectedindex to 0
codeTriggered = true;
comboBox.SelectedIndex = 0;
codeTriggered = false;

// In your SelectionChanged event handler
if (!codeTriggered)
{
// Do stuff when user initiated the selection changed
}

关于c# - 在不触发 SelectionChanged 事件的情况下设置 Combobox 的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21916483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com