Copy / Clone WPF User Control

Copy / Clone WPF User Control

Sometimes you need to copy/clone your user controls. I found this link very useful and hope others find it useful.
In short, you create an extension method that takes type T. Using XamlWriter you save the control into xaml and then read that xaml back out as an object.
Here’s the code:

public static class ExtensionMethods
{
	public static T XamlClone(this T original) where T : class
	{
		if (original == null)
			return null;

		object clone;
		using (var stream = new MemoryStream())
		{
			XamlWriter.Save(original, stream);
			stream.Seek(0, SeekOrigin.Begin);
			clone = XamlReader.Load(stream);
		}

		if (clone is T)
			return (T)clone;
		else
			return null;
	}
}

https://gist.github.com/jon-kim/c209cb196d54ce9b8ad703ddc265c49e

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.