【问题标题】:How to make Command binding to CheckBox in ListView?如何使命令绑定到 ListView 中的 CheckBox?
【发布时间】:2021-12-01 20:41:37
【问题描述】:

问题实际上如标题所述。如果CheckBox在外面,我可以进行如下的命令绑定,它工作正常。

如果我将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; }
}

【问题讨论】:

    标签: c# wpf mvvm data-binding command


    【解决方案1】:

    如果我将它包含在 listView 中,则绑定我的复选框的向上命令将不起作用。

    如果您的CheckBoxListViewItemTemplate 中定义,则其DataContext 将设置为checkMessageList 中为其创建的项目,而不是@987654326 的数据上下文@。

    您在下面的原始绑定需要集合中绑定到ItemSource 的项目的属性CheckBoxCommand。如果您将命令添加到您的项目模型,此绑定应该可以工作。

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

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

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

    【讨论】:

    • 谢谢。我明白你的意思。连接到错误的位置会导致问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2011-09-01
    • 2021-01-18
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多