![](/img/trans.png)
[英]Getting a WPF control to trigger and set another control's itemssource
[英]Filter itemssource of one control with the selected value of another control in WPF
我在WPF窗口中有一个组合框和一个列表框。
组合框的itemssource设置为所有Team对象的列表。 团队有2个属性(TeamId和TeamName)。
列表框的itemssource设置为所有Player对象的列表。 玩家属性中的玩家是TeamId。
我想过滤列表框中的玩家列表,以仅显示其TeamId与组合框中的SelectedItem的TeamId匹配的那些Player。
我宁愿在XAML中全部执行此操作,但是我不确定在C#中执行哪种正确方法。 任何帮助,将不胜感激。
我不确定您是否可以完全在xaml中完成此操作,我认为您可能需要在其他地方进行一些工作。 这就是我做其他事情的方式。
在您的xaml中用CollectionViewSource包装您的收藏集(这样可以对特定属性名称进行排序):
<CollectionViewSource x:Key="ViewName" Source="{Binding YourBinding}">
<CollectionViewSource.SortDescriptions>
<comp:SortDescription PropertyName="Name" Direction="Ascending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
在其他地方,绑定您的listview以将此源作为itemssource:
<ListView x:Name="MyList" ItemsSource="{Binding Source={StaticResource ViewName}}" />
然后在代码中的某个地方,我在一个文本框属性更改侦听器上找到了我,但您了解了一般想法。 ICollectionView接口具有一个筛选器成员,您可以使用该成员将内容过滤掉。
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var text = FilterTextBox.Text;
var source = MyList.Items as ICollectionView;
if (string.IsNullOrWhiteSpace(filter))
{
source.Filter = null;
}
else
{
source.Filter = delegate(object item)
{
var s = item as INamedItem;
return s.Name.IndexOf(filter, StringComparison.CurrentCultureIgnoreCase) != -1;
};
}
}
首先,将所有绑定的集合更改为ObservableCollection。
然后,在组合框上,将SelectedValue绑定到Team类型的DataContext上的另一个属性(您已经实现INotifyPropertyChanged吗?)。 当SelectedValue更改时,使用所有播放器的集合中的过滤列表刷新ListBox的绑定集合:
public ObservableCollection<Team> Teams { get;set;}
public ObservableCollection<Player> Players { get;set;}
private List<Player> AllPlayers {get;set}
public Team CurrentTeam
{
get
{
return this._currentTeam;
}
set
{
this._currentTeam = value;
this.Players = new ObservableCollection(this.AllPlayers.Where(x => x.TeamId = this._currentTeam.TeamId));
RaisePropertyChanged("CurrentTeam");
}
}
这是最快,最轻松的方法。 您可能可以通过CollectionView实现此目的,但是我认为这更容易理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.