Listview DataTemplate 中的 WPF CheckBox 命令

WPF CheckBox Command inside a Listview DataTemplate

我的复选框命令不起作用。我想在选中或取消选中 SelectedItem 时将 ListView 的 SelectedItem 传递给 Command,但 Command 根本不执行。我还怀疑我的 CommandParameter 配置不正确?

我很确定问题是因为 CheckBox 在 ListView DataTemplate 中。

有人可以告诉我如何设置吗?我试图遵循我发现的例子,但似乎没有任何效果。谢谢。

XAML

<ListView x:Name="lvReferralSource" ItemsSource="{Binding ReferralSourceTypeObsCollection}" Style="{StaticResource TypeListViewStyle}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Vertical">
      <CheckBox x:Name="ckbReferralIsChecked" Content="{Binding Value}" IsChecked="{Binding Active}" Style="{StaticResource CheckBoxStyleBase2}"
       Command="{Binding CheckBoxIsChecked}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}, Path=SelectedItem}">
      </CheckBox>
      </StackPanel>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

代码

private ICommand _CheckBoxIsChecked;
public ICommand CheckBoxIsChecked
{
    get
    {
        if (_CheckBoxIsChecked == null)
        {
            _CheckBoxIsChecked = new RelayCommand<object>(ExecuteCheckBoxIsChecked, CanExecuteCheckBoxIsChecked);
        }

        return _CheckBoxIsChecked;
    }
}
public bool CanExecuteCheckBoxIsChecked(object parameter)
{
    return true;
}
public void ExecuteCheckBoxIsChecked(object parameter)
{
    Mouse.OverrideCursor = Cursors.Wait;

    if (parameter != null)
    {
        //Do Stuff...
    }

    Mouse.OverrideCursor = Cursors.Hand;
}

只要 CheckBoxIsChecked 属性 属于定义了 ValueActive 属性的数据对象,您的命令就会被执行。

如果它属于视图模型,您可以使用 RelativeSource:

绑定到它
<CheckBox x:Name="ckbReferralIsChecked" Content="{Binding Value}" IsChecked="{Binding Active}"
            Style="{StaticResource CheckBoxStyleBase2}"
            Command="{Binding DataContext.CheckBoxIsChecked, RelativeSource={RelativeSource AncestorType=ListView}}" 
            CommandParameter="{Binding}">