I'm builing a Windows Phone 8 app using LINQ-to-SQL for my entities. My current implementation uses the simple INotifyPropertyChanging/INotififyPropertyChanged methods:
[Table]
public class Item : INotifyPropertyChanged, INotifyPropertyChanging
{
private int _itemId;
[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", AutoSync = AutoSync.OnInsert)]
public int ItemId
{
get { return _itemId; }
set
{
if (_itemId != value)
{
NotifyPropertyChanging("ItemId");
_itemId = value;
NotifyPropertyChanged("ItemId");
}
}
}
[Column]
internal int? _groupId;
private EntityRef<Board> _group;
[Association(Storage = "_group", ThisKey = "_groupId", OtherKey = "GroupId", IsForeignKey = true)]
public Group Group
{
get { return _group.Entity; }
set
{
NotifyPropertyChanging("Group");
_group.Entity = value;
if (value != null)
{
_groupId = value.BoardId;
}
NotifyPropertyChanging("Group");
}
}
}
I want to change the property setter to my new method, I've founded here: http://danrigby.com/2012/04/01/inotifypropertychanged-the-net-4-5-way-revisited/
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (object.Equals(storage, value)) return false;
this.OnPropertyChanging(propertyName);
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
It's easy to implement for a property like ItemId, but I don't know how to implement it for GroupId because the value should be set on _group.Entity and this can not be passed as reference.
This is my workaround (not tested yet), but I think the PropertyChanging/PropertyChanged events will be raised to early:
public Group Group
{
get { return _group.Entity; }
set
{
var group = _group.Entity;
if (SetProperty(ref group, value))
{
_group.Entity = group;
if (value != null)
{
_groupId = value.GroupId;
}
}
}
}
Is there clear solution for this issue?
I have found a solution. Just overload the method with another implementation:
protected T SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
{
return value;
}
NotifyPropertyChanging(propertyName);
field = value;
NotifyPropertyChanged(propertyName);
return value;
}
protected T SetProperty<T>(ref EntityRef<T> field, T value, [CallerMemberName] string propertyName = null) where T : class
{
NotifyPropertyChanging(propertyName);
field.Entity = value;
NotifyPropertyChanged(propertyName);
return value;
}
Call it like this:
public Group Group
{
get { return _board.Entity; }
set
{
if (SetProperty(ref _group, value) != null)
{
_groupId = value.GroupId;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With