I want to merge two model objects such that fields not null in new object updates the field of old one. But I am getting Invalid cross thread access
in doing so. This is what I am doing:
I have this BaseJson
and User
classes in Application.Models
namespace:
BaseJson
[DataContract]
public class BaseJson
{
public void MergeFrom(BaseJson baseJson)
{
if (baseJson != null)
{
try
{
// http://stackoverflow.com/questions/8702603/merging-two-objects-in-c-sharp
//Type t = typeof();
var Properties = baseJson.GetType().GetProperties();
//var properties = t.GetProperties();//.Where(prop => prop.CanRead && prop.CanWrite);
foreach (var Property in Properties)
{
var value = Property.GetValue(baseJson, null);
if (value != null)
Property.SetValue(this, value, null);
}
}
catch
{
throw new Exception("Error Merging.");
}
}
}
}
User
public class User : BaseJson, INotifyPropertyChanged
{
private string _uid;
[DataMember(Name="uid")]
public string Uid
{
get { return this._uid; }
set { SetField(ref _uid, value, "Uid"); }
}
// Other similar properties
private void SetField<T>(ref T field, T value, string memberName=null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
RaisePropertyChanged(memberName);
}
App.GetUserManager().SaveUserLocally(this);
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
// gives invalid cross thread access error here
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
For two user objects u1 and u2, I am calling
u1.MergeFrom(u2)
from different class ViewModel.cs
.
My problem is, sometimes it doesn't give any error but for others it gives Invalid cross thread access
in RaisePropertyChanged
method.