locked
Clone my object in model RRS feed

  • Question

  • hello,

    how can I clone my object defined in my model that implements INotifyPropertyChanged ?

    thanks

    Friday, May 8, 2015 6:31 AM

Answers

  • Assuming you mean a deep clone.

    Mark your class

    [Serializable]
    ( That goes before the public class .... )

    Add an extension method:

    public static class ExtensionMethods
    {
        // Deep clone
        public static T DeepClone<T>(this T a)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, a);
                stream.Position = 0;
                return (T) formatter.Deserialize(stream);
            }
        }
    }

    Use it

    MyModelType copy = myInstanceOfit.DeepClone();

    Follow the advice here:

    http://stackoverflow.com/questions/129389/how-do-you-do-a-deep-copy-an-object-in-net-c-specifically

    You may well find issues is you inherit from mvvm light viewmodelbase because it doesn't serialise.

    That's one of the reasons I use my own base class NotifyUIBase.

        public class NotifyUIBase : INotifyPropertyChanged
        {
            // Very minimal implementation of INotifyPropertyChanged matching msdn
            // Note that this is dependent on .net 4.5+ because of CallerMemberName
            public event PropertyChangedEventHandler PropertyChanged;
            public void RaisePropertyChanged([CallerMemberName] String propertyName = "")
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                }
            }
        }


    Hope that helps.

    Technet articles: Uneventful MVVM; All my Technet Articles


    • Edited by Andy ONeill Friday, May 8, 2015 7:07 AM
    • Marked as answer by Stefano74 Friday, May 8, 2015 7:26 AM
    Friday, May 8, 2015 7:05 AM