WPF组合框阻止按代码选择项上的事件

本文关键字:选择 事件 代码 组合 WPF | 更新日期: 2023-09-27 18:21:14

我在EDIT 2中重新表述了我的问题

总之,我在WPF中有一个组合框。当我设置SelectedIndex属性时,它会触发SelectionChanged事件,这是正确的行为。但我想要的是,当我用程序设置SelectedIndex属性时,使ComboBox不触发事件。有办法做到吗?

我正在使用.Net 4.5

第1版:代码

public void AddLocation()
{
    List<String> locations = new List<String>();
    //LocationBox is the name of ComboBox
    LocationBox.ItemsSource = locations;
    locations.Add("L1");
    locations.Add("B1");
    locations.Add("B3");
    LocationBox.SelectedIndex = 2; //<-- do not want to raise SelectionChanged event programmatically here
    locations.Add("G1");
    locations.Add("G2");
    locations.Add("F1");
    locations.Add("F3");
}
private void LocationBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Console.WriteLine(LocationBox.SelectedIndex);
}

编辑2:重新表述问题

我想在ComboBox中静默地选择一个项目,即无需用户交互(使用代码/编程),这样它就不会触发SelectionChanged事件。我该怎么做?

WPF组合框阻止按代码选择项上的事件

此答案的注意事项:

  • 这太让人生气了
  • 这太糟糕了

我给你的好处是怀疑,也许你正处于修改现有代码的困境中(或者可能是其他一些原因)。给定示例代码,您可以通过以下代码实现您想要实现的目标:

// Remove the handler
LocationBox.SelectionChanged -= LocationBox_SelectionChanged;
// Make a selection...
LocationBox.SelectedIndex = 2; //<-- do not want to raise SelectionChanged event programmatically here
// Add the handler again.
LocationBox.SelectionChanged += LocationBox_SelectionChanged;

我的猜测是,在初始化组合时,您试图不触发事件。您可以使用DataBinding来完成此操作。下面有一个示例,但您可以搜索MVVM模式以获取更多详细信息。

XAML:

<ComboBox ItemsSource="{Binding CBItems}"
          SelectedIndex="{Binding SelectedCBItem}" />

CS:

public class ModelExample : INotfyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private int selectedCBItem;
    public int SelectedCBItem
    {
        get { return selectedCBItem; }
        set
        {
            selectedCBItem = value;
            NotifyPropertyChanged(nameof(SelectedCBItem));
        }
    }
    private List<ComboBoxItem> cbItems;
    public List<ComboBoxItem> CBItems
    {
        get { return cbItems; }
        set
        {
            cbItems= value;
            NotifyPropertyChanged(nameof(CBItems));
        }
    }
    private void NotifyPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
public class ExampleWindow
{
    ...
    private ModelExample Model;
    private void Initialize()
    {
        ...
        this.DataContext = Model = new ModelExample();
        List<ComboBoxItem> items = // initialize your items somehow
        items.Add(new ComboBoxItem() { Content = "dummy item 1" });
        items.Add(new ComboBoxItem() { Content = "dummy item 2" });
        Model.CBItems = items;
        Model.SelectedCBItem = 1;
    }
}