WPF MVVM: EventTrigger is not working inside CheckBox

核能气质少年 提交于 2019-12-11 16:54:58

问题


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


来源:https://stackoverflow.com/questions/45438801/wpf-mvvm-eventtrigger-is-not-working-inside-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!