如何在绑定到列表上设置选择条件
本文关键字:设置 选择 条件 列表 绑定 | 更新日期: 2023-09-27 18:35:42
我对WPF很陌生,我正在玩绑定。我设法将绑定设置为List
,以便显示例如网格中的人员列表。我现在想要的是在绑定上设置一个条件,并仅从网格中选择满足此条件的人员。到目前为止,我所拥有的是:
// In MyGridView.xaml.cs
public class Person
{
public string name;
public bool isHungry;
}
public partial class MyGridView: UserControl
{
List<Person> m_list;
public List<Person> People { get {return m_list;} set { m_list = value; } }
public MyGridView() { InitializeComponent(); }
}
// In MyGridView.xaml
<UserControl x:Class="Project.MyGridView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<DataGrid Name="m_myGrid" ItemsSource="{Binding People}" />
</Grid>
</UserControl>
我现在想要的是,只在列表中包括饥饿Person
实例。我知道一种在代码中执行此操作的方法,例如添加一个新属性:
public List<Person> HungryPeople
{
get
{
List<Person> hungryPeople = new List<Person>();
foreach (Person person in People)
if (person.isHungry)
hungryPeople.Add(person);
return hungryPeople;
}
}
,然后将绑定更改为HungryPeople
。但是,我认为这不是一个不错的选择,因为它涉及创建额外的公共属性,这可能不可取。有没有办法在 XAML 代码中实现所有这些?
使用带有过滤器的 CollectionViewSource:
绑定:
<UserControl x:Class="Project.MyGridView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Resources>
<CollectionViewSource x:key="PeopleView" Source="{Binding People} Filter="ShowOnlyHungryPeople" />
</UserControl.Resources>
<Grid>
<DataGrid Name="m_myGrid" ItemsSource="{Binding Source={StaticResource PeopleView}}" />
</Grid>
</UserControl>
过滤器:
private void ShowOnlyHungryPeople(object sender, FilterEventArgs e)
{
Person person = e.Item as Person;
if (person != null)
{
e.Accepted = person.isHungry;
}
else e.Accepted = false;
}
您不需要多个属性,只需为 Person
类创建一个ObservableCollection
并绑定到ItemsSource
DataGrid
。
public ObservableCollection<Person> FilterPersons{get;set;}
<DataGrid Name="m_myGrid" ItemsSource="{Binding FilterPersons}" />
使用视图构造函数中的主列表People
初始化此集合。
在每个过滤器(例如,匈牙利,口渴等)上,只需从FilterPersons
中添加/删除Person
,您的DataGrid
就会相应地更新。
您可以在绑定中使用转换器,在那里您可以根据需要过滤列表,并返回过滤的列表。
<DataGrid Name="m_myGrid" ItemsSource="{Binding People, Converter=myConverter}" />
而转换器——
public class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
List<Person> hungryPeople = new List<Person>();
foreach (Person person in value as List<Person>)
if (person.isHungry)
hungryPeople.Add(person);
return hungryPeople;
}
}