I have a simple wpf checkbox
<CheckBox Name="layerCheckBox" IsChecked="{Binding Path=IsSelected, Mode=TwoWay}" Grid.Column="0" />
which I bind to a BindingList of my custom Layer class.
public BindingList<Layer> Layer
{
get { return _layer; }
set { _layer = value; }
}
The Layer class has a property IsSelected. Thats what I use in my checkbox. As you can see I added some output for reading and writing the property
public bool IsSelected
{
get
{
System.Diagnostics.Debug.WriteLine("get"+_isSelected+this.GetHashCode()+
"thread"+Thread.CurrentThread.ManagedThreadId);
return _isSelected;
}
set
{
System.Diagnostics.Debug.WriteLine("set" + value + this.GetHashCode()
+ "thread" + Thread.CurrentThread.ManagedThreadId);
PropertyChanged.ChangeAndNotify(ref _isSelected, value, () => IsSelected);
}
}
The weird thing is the output. First of all I check the checkbox and the property is set to true. Afterwards I read the property and it says false? Whats going on? Its the same object (hashcode) and the same thread… I don’t get it… And for the next 2 reads, I guess that the refresh, it is true again. The best part is – if I uncheck the box it returns true.
The code inside the property is from here property notify
the output
setTrue53182860thread1
getFalse53182860thread1
getTrue53182860thread1
getTrue53182860thread1
What might be the issue is the
ChangeAndNotifyextension method. It sets the value of your field after the raising of the property changed event.When you raise the event all subscribers will attempt to read from the property. Because the backing field has not been set yet it will return the original value.
Fix the code in the
ChangeAndNotifyextension method to set the value of the field before the raising of the Property Change event.