Search code examples
c#.netwpfdata-binding

Dynamic filtering with an ItemsControl combobox


I have this situation where I want to display a list of Administration objects and a ComboBox for each Administration. Inside this ComboBox I want a list with Employees belonging to this Administration, along with an empty option. So I need to filter based on Administration.

So far I've come up with the following code (note: object names have been translated)

<ItemsControl x:Name="listAdministrations" ItemsSource="{Binding Path=AllAdministrations}" Margin="0,0,0,6">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical" >
                <TextBox Content="{Binding Path=AdministrationName}" />

                <StackPanel Orientation="Horizontal" Margin="14,0,0,0">
                    <Label>Declares under:</Label>
                    <ComboBox DisplayMemberPath="DisplayFullName">
                        <ComboBox.ItemsSource>
                            <CompositeCollection>
                                <!-- empty option -->
                                <model:Employee DisplayFullName="-" />
                                <CollectionContainer Collection="{Binding Source={StaticResource employeeCV}}"/>
                            </CompositeCollection>
                        </ComboBox.ItemsSource>
                    </ComboBox>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

The static resource employeeCV is a CollectionViewSource with a Filter event attached. But I have to somehow pass the current Administration in the ItemsControl loop to this event. In data binding, this translates to {Binding Path=.} within the ItemsControl. The sender object is my CollectionViewSource but this provides no useful data.

Something like this:

private void EmployeeAdministrationFilter( object sender, FilterEventArgs e )
    {
        Employee employee = ( Employee )e.Item;
        Administration administration; // how do I pass the administration to this filter?
}

Solution

  • I don't know how to do exactly what you ask, but I can suggest an alternate approach: create an extension method for your Administration class. This method creates a filtered collection view and returns it. You can then bind to the result of the method.