如何在ItemsSource更改时静音SelectionChanged?

4

我有一个绑定了数据的ComboBox,它还监听SelectionChanged事件。

然而,当ItemsSource发生变化时,SelectionChanged事件也会被触发。这只会在ItemsSource是视图时发生。

是否有办法只在用户操作时才触发SelectionChanged事件,而不是在ItemsSource属性变化时触发?


1
http://stackoverflow.com/questions/6265107/silverlight-mvvm-stop-selectionchanged-triggering-in-response-to-itemssource-res - Bolu
2个回答

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
我发现了这个方法:

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

    ///your code

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接