ListViewItem with CheckBox IsChecked Binding to ViewModel

泪湿孤枕 提交于 2019-12-07 18:59:32

问题


I have a ListView with a DataTemplate for displaying for each ListViewItem a 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:

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?

My code doesn't work.


回答1:


Try this

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



回答2:


Remove 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



来源:https://stackoverflow.com/questions/23359550/listviewitem-with-checkbox-ischecked-binding-to-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!