/// 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
Post a Comment