WPF ComboBox按代码阻止选择项目上的事件

时间:2015-11-10 02:14:19

标签: c# .net wpf

我在编辑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事件。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

对此答案的警告:

  • 这是hackish。
  • 这很糟糕。

我怀疑你可能会遇到修改现有代码(或者其他一些原因)的困境。给出示例代码,您可以通过此代码完成您要实现的目标:

// 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;

答案 1 :(得分:0)

我的猜测是你在初始化组合时试图不发射事件。您可以使用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;
    }
}