-->

WPF MVVM: EventTrigger is not working inside Check

2019-08-17 19:39发布

问题:

I'm building an application with WPF in MVVM style. I'm trying to make filter on my DataGrid when I check or uncheck several CheckBoxes for filtering.

I've found solution with Interaction.Triggers, but it's not working for me in this case.

Here is my code:

<ListBox 
            ItemsSource="{Binding PortsFilterSource}"
            Background="LightGray"
            BorderThickness="0"
            Grid.Column="1">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox 
                        Content="{Binding Name}"
                        IsChecked="{Binding IsChecked}">

                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="Unchecked">
                                <i:InvokeCommandAction Command="{Binding FilterCommand}"/>
                            </i:EventTrigger>
                            <i:EventTrigger EventName="Checked">
                                <i:InvokeCommandAction Command="{Binding FilterCommand}"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>
                    </CheckBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Everything is working great except FilterCommand. I have this in my C# code:

public DelegateCommand<object> FilterCommand { get; set; }
...
FilterCommand = new DelegateCommand<object>(Filter);

Filter(object obj) is a function, but it is not entered when I check or uncheck any of my CheckBoxes.

Any help would be very appreciated.

回答1:

The problem is, that the data context of the list item is of type FilterModel, but the FilterCommand is in the parent view model.

Try the following binding for the command:

{Binding DataContext.FilterCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}