为什么引用ListCollectionView的ComboBox.ItemsSource会更改ComboBox.Sele

本文关键字:ComboBox Sele ItemsSource ListCollectionView 为什么 引用 | 更新日期: 2023-09-27 17:58:49

假设我有3个ComboBox控件。每个ItemsSource引用相同的产品主列表。每个SelectedItem引用另一个所选产品列表的单独数组索引。这一切都很好,程序运行如预期。

现在假设我想过滤产品的主列表(例如,仅包含特定字符串"berry"的产品)。将ItemsSource从Products更改为ProductsView会导致两件事:

  1. 组合框确实经过了适当的过滤
  2. 无论何时进行选择,所有组合框都设置为最后一次选择

这是代码。尝试在ItemsSource="{Binding Path=ProductsView}"ItemsSource="{Binding Path=Products}" 之间切换

主窗口.xaml:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <ComboBox ItemsSource="{Binding Path=ProductsView}" SelectedItem="{Binding Path=SelectedProducts[0]}" />
        <ComboBox ItemsSource="{Binding Path=ProductsView}" SelectedItem="{Binding Path=SelectedProducts[1]}" />
        <ComboBox ItemsSource="{Binding Path=ProductsView}" SelectedItem="{Binding Path=SelectedProducts[2]}" />
    </StackPanel>
</Window>

主窗口.xaml.cs:

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Data;
namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        public List<Product> Products { get; set; }
        public ListCollectionView ProductsView { get; set; }
        public ObservableCollection<Product> SelectedProducts { get; set; }
        public MainWindow()
        {
            Products = new List<Product>();
            Products.Add(new Product { Name = "Apple" });
            Products.Add(new Product { Name = "Orange" });
            Products.Add(new Product { Name = "Banana" });
            Products.Add(new Product { Name = "Pear" });
            Products.Add(new Product { Name = "Strawberry" });
            Products.Add(new Product { Name = "Raspberry" });
            ProductsView = new ListCollectionView(Products);
            ProductsView.Filter = (x) => (x as Product).Name.Contains("berry");
            SelectedProducts = new ObservableCollection<Product>();
            SelectedProducts.Add(null);
            SelectedProducts.Add(null);
            SelectedProducts.Add(null);
            InitializeComponent();
            DataContext = this;
        }
    }
    public class Product
    {
        public string Name { get; set; }
        public override string ToString()
        {
            return Name;
        }
    }
}

为什么引用ListCollectionView的ComboBox.ItemsSource会更改ComboBox.Sele

使用视图时,SelectedItem与CurrentItem同步。抑制同步集属性:

IsSynchronizedWithCurrentItem="False"

在组合框上。