简体   繁体   English

ListViewItem与CheckBox IsChecked绑定到ViewModel

[英]ListViewItem with CheckBox IsChecked Binding to ViewModel

I have a ListView with a DataTemplate for displaying for each ListViewItem a Checkbox. 我有一个带有DataTemplate的ListView,用于为每个ListViewItem显示一个Checkbox。

在此输入图像描述

<ListView ItemsSource="{Binding TableNames}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding}" IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected, Mode=TwoWay}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

The ItemsSource ("TableNames") is deklared in the ViewModel like this: ItemsSource(“TableNames”)在ViewModel中被解除,如下所示:

private ObservableCollection<Item> _TableNames = new ObservableCollection<Item>();
public ObservableCollection<Item> TableNames
{
    get { return _TableNames; }
    set
    {
        _TableNames = value;
        OnPropertyChanged("TableNames");
    }
}

public class Item
{
    public bool IsSelected { get; set; }

    public string Name { get; set; }

    public override string ToString()
    {
        return this.Name;
    }
}

How can I bind the IsChecked from the Checkbox to the Item.IsSelected property? 如何将Checkbox中的IsChecked绑定到Item.IsSelected属性?

My code doesn't work. 我的代码不起作用。

Try this 尝试这个

<DataTemplate>    
<CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}" />
</DataTemplate>

Remove RelativeSource 删除RelativeSource

<CheckBox Content="{Binding}" IsChecked="{Binding IsSelected}" />

Since DataContext of ListViewItem will be set to instance of Item all you need to specify is path to IsSelected 由于ListViewItem DataContext将被设置为Item实例,因此您需要指定的是IsSelected路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM