首页 > 解决方案 > Listview DataTemplate 中的 WPF CheckBox 命令

问题描述

我的 CheckBox 命令不起作用。我想在选中或未选中选定的ITITEM时将listView的SelectedItem传递到命令中,但是该命令根本不执行。我还怀疑我的 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;
}

标签: c#wpflistviewcheckboxdatatemplate

解决方案


如果属性属于定义和属性CheckBoxIsChecked的数据对象,则应执行您的命令。ValueActive

如果它属于视图模型,您可以使用 a 绑定到它RelativeSource

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

推荐阅读