首页 > 解决方案 > WPF - 复选框命令未触发

问题描述

我正在使用 MVVM 模式编写 WPF 应用程序,但遇到以下问题:我已将命令绑定到 UI 中的复选框,但是单击复选框时未调用事件处理程序。我已经使用相同的方法来绑定其他 UI 元素(例如按钮),并且它似乎对它们工作正常。相关的xaml如下:

<ListBox ItemsSource="{Binding ElementsMethods}" Height="auto" x:Name="MethodsListBox">
                                        <ListBox.ItemTemplate>
                                            <DataTemplate>
                                                <StackPanel Orientation="Horizontal">
                                                    <TextBlock Text="{Binding FormattedEM}"/>
                                                    <StackPanel Orientation="Horizontal">
                                                        <TextBlock Text="Started"/>
                                                        <Checkbox IsChecked="{Binding Started} Command="{Binding elementMethodCheckboxChangeCommand}"> </CheckBox>
                                                    </StackPanel>
                                                    <StackPanel Orientation="Horizontal">
                                                        <TextBlock Text="Finished"/>
                                                        <CheckBox IsChecked="{Binding Finished}"></CheckBox>
                                                    </StackPanel>
                                                </StackPanel>
                                            </DataTemplate>
                                        </ListBox.ItemTemplate>IsChecked="{Binding Finished}

其中 elementMethodCheckboxChangeCommand 是我的 viewmodel 类中 ICommand 类型的公共属性:

public ICommand elementMethodCheckboxChangeCommand { get; set; }

用于设置此属性的具体类名为中继命令:

elementMethodCheckboxChangeCommand = new RelayCommand(new Action<object>(elementMethodCheckboxChange));

其中 elementMethodCheckboxChange 是一个公共 void 函数,采用对象类型的参数。relaycommand类的实现如下:

class RelayCommand : ICommand
{
    private Action<object> _action;
    public RelayCommand(Action<object> action)
    {
        _action = action;
    }
    public bool CanExecute(object parameter)
    {
        return true;
    }
    public void Execute(object parameter)
    {
        if (parameter != null)
        {
            _action(parameter);
        }
        else
        {
            _action("Hello world");
        }
    }
    public event EventHandler CanExecuteChanged;
}

就像我在上面所说的那样,我使用相同的方法绑定到我的 UI 中的按钮并且它们按预期工作,但是当我单击复选框时根本没有任何反应,并且我的事件处理程序没有执行。

我希望有人可以在这里帮助我,因为这个问题开始变得非常令人沮丧 - 请询问您是否需要任何其他信息。谢谢大家 :)

标签: c#wpfxamlmvvmbinding

解决方案


RelativeSource当您想要绑定到 `ItemTemplate 中的视图模型的属性时,您应该指定一个绑定:

<CheckBox ... Command="{Binding DataContext.elementMethodCheckboxChangeCommand,
            RelativeSource={RelativeSource AncestorType=ListBox}}"/>

默认DataContext值为 中的当前项,ItemsSource并且该项没有elementMethodCheckboxChangeCommand要绑定的属性。

使属性静态不是一个很好的解决方案。


推荐阅读