【问题标题】:WPF MVVM: EventTrigger is not working inside CheckBoxWPF MVVM:EventTrigger 在 CheckBox 内不起作用
【发布时间】:2018-01-08 09:04:53
【问题描述】:

我正在使用 MVVM 样式的 WPF 构建应用程序。当我选中或取消选中多个 CheckBox 进行过滤时,我正在尝试对我的 DataGrid 进行过滤。

我找到了 Interaction.Triggers 的解决方案,但在这种情况下它对我不起作用。

这是我的代码:

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

除了FilterCommand,一切都很好。我的 C# 代码中有这个:

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

Filter(object obj) 是一个函数,但是当我选中或取消选中我的任何 CheckBox 时,它没有被输入。

任何帮助将不胜感激。

【问题讨论】:

  • 为什么不用IsChecked的setter调用Filter
  • 调试的时候看看输出窗口,有没有绑定错误?
  • 哦,是的,我有:System.Windows.Data 错误:40:BindingExpression path error: 'FilterCommand' property not found on 'object' ''FilterModel' (HashCode=57774494)'. BindingExpression:Path=FilterCommand; DataItem='FilterModel' (HashCode=57774494); target element is 'InvokeCommandAction' (HashCode=8505800); target property is 'Command' (type 'ICommand')
  • @JanDotNet 我在与Filter 方法不同的文件中有一个对象FilterModel。它不能是静态的。有没有其他方法可以调用它?
  • 但是FilterCommandIsChecked 属性在同一个类中,不是吗?

标签: c# wpf checkbox mvvm eventtrigger


【解决方案1】:

问题是,列表项的数据上下文是FilterModel 类型,但FilterCommand 在父视图模型中。

为命令尝试以下绑定:

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

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 2013-04-12
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多