问题描述
说我有3个 ComboBox
控件.每个 ItemsSource
都引用相同的产品主列表.每个 SelectedItem
都引用另一个选定产品列表的单独数组索引.这一切都很好,程序可以按预期工作.
Say I have 3 ComboBox
controls. Each ItemsSource
references the same master list of products. Each SelectedItem
references a separate array index of another list of selected products. This all works great, the program works as expected.
现在说我想过滤产品的主列表(例如,仅包含特定字符串"berry"的产品).将ItemsSource从Products更改为ProductsView会导致两件事:
Now say I want to filter the master list of products (for example, only those containing a specific string "berry"). Changing the ItemsSource from Products to ProductsView results in 2 things:
- 组合框确实已正确过滤
- 每当做出选择时,所有组合框都将设置为最后一个选择
这是代码.尝试在 ItemsSource ="{Binding Path = ProductsView}"
和 ItemsSource ="{Binding Path = Products}"
MainWindow.xaml:
MainWindow.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>
MainWindow.xaml.cs:
MainWindow.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;
}
}
}
推荐答案
使用视图时,SelectedItem与CurrentItem同步.要取消同步集属性:
When using a view the SelectedItem is synchronized with the CurrentItem. To suppress the synchronization set property:
IsSynchronizedWithCurrentItem="False"
在组合框上.
这篇关于为什么引用ListCollectionView的ComboBox.ItemsSource更改ComboBox.SelectedItem行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!