Question

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.

Was it helpful?

Solution

Try this

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top