如何在绑定到列表上设置选择条件?

Yel*_*low 1 c# wpf binding

我是WPF的新手,我正在玩Bindings.我设法将绑定设置为a List,以便显示例如网格中的人员列表.我现在想要的是在Binding上设置一个条件,并且只选择满足这个条件的网格中的人.到目前为止我所拥有的是:

// 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>
Run Code Online (Sandbox Code Playgroud)

我现在想要的是,只在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将Binding更改为HungryPeople.但是,我发现这不是一个很好的选择,因为它涉及制作额外的公共属性,这可能是不可取的.有没有办法在XAML代码中实现所有这些?

Alb*_*rto 5

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>
Run Code Online (Sandbox Code Playgroud)

过滤器:

private void ShowOnlyHungryPeople(object sender, FilterEventArgs e)
{
    Person person = e.Item as Person;
    if (person != null)
    {
       e.Accepted = person.isHungry;
    }
    else e.Accepted = false;
}
Run Code Online (Sandbox Code Playgroud)