如何在ItemsSource更改时将SelectionChanged静音

时间:2011-07-06 15:12:45

标签: wpf data-binding

我有一个带有ItemsSource数据绑定的ComboBox。此ComboBox还侦听SelectionChanged事件。

但是,当ItemsSource更改时,将引发SelectionChanged事件。仅当ItemsSource是视图时才会发生这种情况。

有没有办法让SelectionChanged仅在用户执行时引发,而不是在ItemsSource属性发生更改时引发?

2 个答案:

答案 0 :(得分:3)

如果您在代码中进行数据绑定,则可以在更改ItemsSource时取消订阅SelectionChanged。见下面的示例代码:

XAML:

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <StackPanel DataContextChanged="OnDataContextChanged">
        <Button Content="Change items" Click="OnClick" />   
        <ComboBox Name="_cb" />
    </StackPanel>

</Window>

代码背后:

public partial class Window1 
{
    public Window1()
    {
        InitializeComponent();

        _cb.SelectionChanged += OnSelectionChanged;

        DataContext = new VM();
    }

    private void OnClick(object sender, RoutedEventArgs e)
    {
       (DataContext as VM).UpdateItems();
    }

    private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
    }

    private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        VM vm = DataContext as VM;
        if (vm != null)
        {
            _cb.ItemsSource = vm.Items;
            vm.PropertyChanged += OnVMPropertyChanged;
        }
        else
        {
            _cb.ItemsSource = null;
        }
    }

    void OnVMPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Items")
        {
            _cb.SelectionChanged -= OnSelectionChanged;
            _cb.ItemsSource = (DataContext as VM).Items;
            _cb.SelectionChanged += OnSelectionChanged;
        }
    }
}

public class VM : INotifyPropertyChanged
{
    public VM()
    {
        UpdateItems();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private List<string> _items = new List<string>();
    public List<string> Items
    {
        get { return _items; }
        set
        {
            _items = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Items"));
            }
        }
    }

    public void UpdateItems()
    {
        List<string> items = new List<string>();
        for (int i = 0; i < 10; i++)
        {
            items.Add(_random.Next().ToString());
        }
        Items = items;
    }

    private static Random _random = new Random();
}

答案 1 :(得分:1)

我找到了方法:

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)    
{ 
   if(!ComboBox.IsDropDownOpen)
    {
    return;
    }

    ///your code

}
相关问题