如果我理解您的问题正确,您需要一种过滤机制。请看一下
ICollectionView
接口及其实现,例如
CollectionViewSource
,这可能会帮助您实现此目标。您需要处理实现过滤逻辑的
Filter
事件。以下是MSDN上的该类(
http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource(v=vs.110).aspx)。一个例子:容器类:
public string Name { get; set; }
public string Capital { get; set; }
public Country(string name, string capital) {
this.Name = name;
this.Capital = capital;
}
模型类:
private ObservableCollection<Country> _countries;
private ICollectionView _european;
private ICollectionView _american;
public ObservableCollection<Country> Countries {
get {
if (_countries == null) {
_countries = new ObservableCollection<Country>();
}
return _countries;
}
}
public ICollectionView European {
get {
if (_european == null) {
_european = new CollectionViewSource {
Source = this.Countries
}.View;
_european.Filter += (e) => {
Country c = e as Country;
if (c.Name == "UK" || c.Name == "Ireland" || c.Name == "France") {
return true;
}
return false;
};
}
return _european;
}
}
public ICollectionView American {
get {
if (_american == null) {
_american = new CollectionViewSource {
Source = this.Countries
}.View;
_american.Filter += (e) => {
Country c = e as Country;
if (c.Name == "USA" || c.Name == "Canada" || c.Name == "Mexico") {
return true;
}
return false;
};
}
return _american;
}
}
初始化代码:
private Model _model;
public Model Model {
get {
if (_model == null) {
_model = new Model();
}
return _model;
}
}
public MainWindow() {
InitializeComponent();
this.DataContext = this.Model;
this.Model.Countries.Add(new Country("UK", "London"));
this.Model.Countries.Add(new Country("Ireland", "Dublin"));
this.Model.Countries.Add(new Country("France", "Paris"));
this.Model.Countries.Add(new Country("USA", "Washington D. C."));
this.Model.Countries.Add(new Country("Mexico", "Mexico City"));
this.Model.Countries.Add(new Country("Canada", "Ottawa"));
}
XAML:
<StackPanel>
<ComboBox
ItemsSource='{Binding Path=European}'>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel
Orientation='Horizontal'>
<TextBlock
Text='{Binding Path=Name}' />
<TextBlock
Text=', ' />
<TextBlock
Text='{Binding Path=Capital}' />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ComboBox
ItemsSource='{Binding Path=American}'>
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel
Orientation='Horizontal'>
<TextBlock
Text='{Binding Path=Name}' />
<TextBlock
Text=', ' />
<TextBlock
Text='{Binding Path=Capital}' />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>