如何在 ListView 中将 Command 绑定到 CheckBox?

How to make Command binding to CheckBox in ListView?

问题其实如题所述。如果 CheckBox 在外面,我可以按如下方式进行命令绑定,它工作正常。

如果我将它包含在 ListView 中,我的 CheckBox 命令绑定将不起作用。另外,当我在模型中创建一个 CheckBoxCommand 时,没有绑定错误,但我不知道如何在我的模型中使用 CheckBoxCommand

<CheckBox>
    <i:Interaction.Triggers>
       <i:EventTrigger EventName="Click">
            <i:InvokeCommandAction Command="{Binding CheckBoxCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</CheckBox>

视图模型

 public RelayCommand CheckBoxCommand { get; set; }

 public AnalysisViewModel()
 {
     CheckBoxCommand = new RelayCommand(CheckBoxClick);
 }

 private void CheckBoxClick(object param)
 {
     Console.WriteLine("Click");
 }

以下情况无效。在以下情况下,我如何运行它与应用程序一起使用?

<ListView ItemsSource="{Binding checkMessageList}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding ID}">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <i:InvokeCommandAction Command="{Binding CheckBoxCommand}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </CheckBox>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListView>

我的模型

public static readonly ObservableCollection<CanBusDataMessageResponse> checkMessageList = new ObservableCollection<CanBusDataMessageResponse>();

public class CanBusDataMessageResponse
{
    public int IDE { get; set; }
    public int ID { get; set; }
    public byte RTR { get; set; }
    public byte DLC { get; set; }
    public byte Byte0 { get; set; }
    public byte Byte1 { get; set; }
    public byte Byte2 { get; set; }
    public byte Byte3 { get; set; }
    public byte Byte4 { get; set; }
    public byte Byte5 { get; set; }
    public byte Byte6 { get; set; }
    public byte Byte7 { get; set; }
    public DateTime Time { get; set; }
}

Up command binding my checkBox doesn't work if I enclose it in a listView.

如果您的 CheckBox 是在 ListViewItemTemplate 中定义的,则其 DataContext 设置为 checkMessageList 中的项目为 ListBox.

的数据上下文创建,而不是

您下面的原始绑定需要 属性 CheckBoxCommand 集合中绑定到 ItemSource 的项目。如果您向项目模型添加命令,此绑定应该有效。

<i:InvokeCommandAction Command="{Binding CheckBoxCommand}"/>

为了绑定到作为 ListView(也包含 checkMessageList)的数据上下文的视图模型中的 CheckBoxCommand,您可以使用 RelativeSource绑定。

<i:InvokeCommandAction Command="{Binding DataContext.CheckBoxCommand, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}"/>