Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you set a select-condition on a Binding to a List?

Tags:

c#

binding

wpf

I am quite new to WPF and I'm playing around with Bindings. I manage to set a Binding to a List in order to display, for example, a list of people in a grid. What I would like now, is to set a condition on the Binding, and to select only people from the grid who satisfy this condition. What I have so far is:

// 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>

What I would like now, is to only include in the list Person instances who are hungry. I know a way to do it in code, by for example adding a new property:

public List<Person> HungryPeople
{
    get 
    {
        List<Person> hungryPeople = new List<Person>();
        foreach (Person person in People)
           if (person.isHungry)
                hungryPeople.Add(person);
        return hungryPeople;
    }
}

and then changing the Binding to HungryPeople instead. However, I don't find this a pretty option, as it involves making extra public properties, which may not be desirable. Is there a way to to all this within the XAML code?

like image 974
Yellow Avatar asked Jan 31 '26 00:01

Yellow


1 Answers

Use a CollectionViewSource with a filter:

The binding:

<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>

The filter:

private void ShowOnlyHungryPeople(object sender, FilterEventArgs e)
{
    Person person = e.Item as Person;
    if (person != null)
    {
       e.Accepted = person.isHungry;
    }
    else e.Accepted = false;
}
like image 74
Alberto Avatar answered Feb 02 '26 14:02

Alberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!