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是我的视图模型类中ICommand类型的公共属性:

public ICommand elementMethodCheckboxChangeCommand { get; set; }

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

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

其中elementMethodCheckboxChange是一个接受object类型参数的公共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中的按钮,它们按预期工作,但当我单击复选框时,什么都不会发生,我的事件处理程序也不会执行。

我希望有人能在这里帮助我,因为这个问题开始变得非常令人沮丧——请询问你是否需要任何其他信息。提前感谢大家:(

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

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

默认的DataContextItemsSource中的当前项,而此项没有可绑定的elementMethodCheckboxChangeCommand属性。

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

最新更新