I want to make two way binding for checkboxes inside ListView. This is my Product class:
public class Product
{
public bool IsSelected { get; set; }
public string Name { get; set; }
}
In ViewModel class I have observable collection of products:
private ObservableCollection<Product> _productList;
public ObservableCollection<Product> ProductList
{
get
{
return _productList;
}
set
{
_productList = value;
}
}
public MainViewModel()
{
ProductList = new ObservableCollection<Product>
{
new Product {IsSelected = false, Name = "Not selected"},
new Product {IsSelected = true, Name = "Selected"},
new Product {IsSelected = true, Name = "Selected"}
};
}
}
And finally I have Grid with ListView that binding my ProductList:
<Grid>
<ListView Height="120" HorizontalAlignment="Left"
VerticalAlignment="Top"
SelectionMode="Multiple"
ItemsSource="{Binding ProductList}" >
<ListView.View>
<GridView>
<GridViewColumn Width="40">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=IsSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="120" Header="Product Name" DisplayMemberBinding="{Binding Path=Name}" />
</GridView>
</ListView.View>
</ListView>
</Grid>
When I debug this app it never arrive to setter's line when I check/uncheck checkboxes. Any ideas what is wrong in this code? Thanks in advance!
For two way binding to work you should first of all implement
INotifyPropertyChanged
event in your view Model and product class to make sure when there is some change in property view is notified instantlyAlso make sure you are setting
DataContext
of view correctlyand as Fischermaen mentioned you won't be able to debug this kind of property you should do something like this if you want to debug
You bound the CheckBox to the IsSelected property. This property is implemented as an auto implemented property. You will never break at the setter or getter in debugger. I can't see any issue in your code, it should work like you've coded it.
You should implement on binded type
INotifyPropertyChanged
interface, and in case whenIsSelected
propertyis set have to notify about it.Docs and sample from msdn:
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx