问题
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