I have found this generic merge method to be very useful. Before you cut and paste it into you Silverlight application, let me explain why I created it.
- public virtual bool MergeValues(object oSource, bool bNotifyUI)
- {
- bool bSucess = true;
- foreach (var oPropInfo in oSource.GetType().GetProperties())
- {
- if (!oPropInfo.CanRead !oPropInfo.CanWrite oPropInfo.Name == "Item")
- continue;
- var oResult = oPropInfo.GetValue(oSource, null);
- if (oResult != oPropInfo.GetValue(this, null))
- try
- {
- oPropInfo.SetValue(this, oResult, null);
- if (bNotifyUI)
- NotifyOfPropertyChange(oPropInfo.Name);
- }
- catch
- {
- bSucess = false;
- }
- }
- return bSucess;
- }
Once Silverlight binds a property to a XAML element, your program will perform a lot better if you just change the value rather then rebind to a new object. I have not done any detailed timing tests, but by using this code in a before / after way you can “feel” that this is faster.
I know there is a performance cost when you access a property via reflection, but I am willing to pay that cost to have a solution that is VERY reliable.
By defining this method as virtual you are able to override to build a version that performs better, for example:
- public override bool MergeValues(object oSource, bool bNotifyUI)
- {
- bool bSucess = true;
- Person oPerson = oSource as Person;
- this.ID = oPerson.ID;
- this.FirstName = oPerson.FirstName;
- this.MiddleName = oPerson.MiddleName;
- this.LastName = oPerson.LastName;
- this.MostRecentFlight = oPerson.MostRecentFlight;
- return bSucess;
- }
But this solution is not as reliable and requires me to change the code every time I modify the properties in this class.
Feel free to cut, paste and modify this code to meet your own coding objectives.