c# - 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 中的按钮并且它们按预期工作,但是当我单击复选框时根本没有任何反应,并且我的事件处理程序没有执行。
我希望有人可以在这里帮助我,因为这个问题开始变得非常令人沮丧 - 请询问您是否需要任何其他信息。谢谢大家 :)
解决方案
RelativeSource
当您想要绑定到 `ItemTemplate 中的视图模型的属性时,您应该指定一个绑定:
<CheckBox ... Command="{Binding DataContext.elementMethodCheckboxChangeCommand,
RelativeSource={RelativeSource AncestorType=ListBox}}"/>
默认DataContext
值为 中的当前项,ItemsSource
并且该项没有elementMethodCheckboxChangeCommand
要绑定的属性。
使属性静态不是一个很好的解决方案。
推荐阅读
- javascript - 单击时功能不起作用,没有任何反应
- javascript - 如何在打字稿中检索 T 类型的泛型类的名称
- deep-learning - 你有没有在训练的时候遇到过类似loss jitter的问题?
- c# - 如何定期向现有组合框添加/更新项目?
- c# - 视图模型之间的绑定属性
- reactjs - 如何以这种格式将道具或状态从父母传递给孩子
- c++ - Catch2:测试崩溃,因为封装在 REQUIRE_THROWS 中的调用抛出异常
- address-sanitizer - 日志控制,用于 Address Sanitizer PLUS Undefined Behavior Sanitizer?
- android - 如何在下图中制作像 Zomato 这样的类别选择器
- php - 如何检查当前时间之间是否有两个日期时间