WPF: How to Deep Copy WPF object (e.g. UIElement) ?



        /// Generic Method to perform Deep-Copy of a WPF element (e.g. UIElement)
        public static T DeepCopy(T element)
        {
            var xaml = XamlWriter.Save(element);
            var xamlString = new StringReader(xaml);
            var xmlTextReader = new XmlTextReader(xamlString);
            var deepCopyObject = (T)XamlReader.Load(xmlTextReader);
            return deepCopyObject;
        }


        /// Test showing that the deep copied object does not have the same reference as the object being copied
        [TestMethod]
        public void DeepCopy()
        {
            // Arrange
            Shape shape = new Rectangle {Fill = new SolidColorBrush(Colors.Red)};
 
            // Act
            var deepCopyShape = MyClass.DeepCopy(shape);
 
            // Assert
            Assert.AreNotSame(shape, deepCopyShape);
        }
 

Comments

Popular posts from this blog

WPF How to Dispose ViewModel when the associated UserControl (Not Window) closes?

C# How to unit test Dispatcher