设置Combobox的选定值而不触发SelectionChanged事件

时间:2014-02-20 18:29:21

标签: c# wpf

我有一个ComboBox:

<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的新手,但肯定不应该像看起来那么复杂?或者我在这里遗漏了什么?

2 个答案:

答案 0 :(得分:8)

无论是通过代码还是通过用户互动设置,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
}

答案 1 :(得分:4)

您可以使用数据绑定解决此问题:

private int _sourceIndex;
public int SourceIndex
{
    get { return _sourceIndex; }
    set
    {
        _sourceIndex= value;
        NotifyPropertyChanged("SourceIndex");
    }
}

private List<ComboBoxItem> _sourceList;
public List<ComboBoxItem> SourceList
{
    get { return _sourceList; }
    set
    {
        _sourceList= value;
        NotifyPropertyChanged("SourceList");
    }
}

public ClientReports()
{
    InitializeComponent();

    // Set the DataContext
    DataContext = this;

    // set the sourceIndex to 0
    SourceIndex = 0;

    // SourceList initialization
    source = ... // get your comboboxitem list
    source.Insert(0, new ComboBoxItem { Content = " - select - "});
    SourceList = source
}

在XAML中绑定SelectedItem和ItemsSource

<ComboBox Name="drpRoute" 
   ItemsSource="{Binding SourceList}"
   SelectedIndex="{Binding SourceIndex}" />

使用数据绑定,每次在代码中更改SourceIndex时,它都会在UI中更改,如果您在UI中更改它,它也会在类中更改,您可以尝试查找有关 MVVM设计模式的教程这是编写WPF应用程序的好方法。

相关问题