我有一个绑定(bind)了 ItemsSource 数据的 ComboBox。此 ComboBox 还监听 SelectionChanged 事件。

但是,当 ItemsSource 更改时,将引发 SelectionChanged 事件。这仅在 ItemsSource 是 View 时发生。

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

最佳答案

如果您在后面的代码中进行数据绑定(bind),则可以在 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();
}

关于wpf - 当 ItemsSource 更改时如何使 SelectionChanged 静音,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6598738/

10-12 22:42