Search code examples
c#wpflistviewcheckboxtemplatebinding

ListViewItem with CheckBox IsChecked Binding to ViewModel


I have a ListView with a DataTemplate for displaying for each ListViewItem a Checkbox.

enter image description here

<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.


Solution

  • Try this

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