none
Copy / Clone user control ? RRS feed

  • Question

  • I have this
     
    userControl uCo ,uCo2  = new userControl ( );
     
    I put value inside ( uCo2 ) and I want to copy this uCo with his values into
    a new userControl .
     
    How could I copy / clone the userControl ( uCo2 ) into ( uCo ) ;
     
    And what is the best way to copy/clone Grids.
     
    Thank a lot.
     
    Wednesday, December 19, 2007 4:43 PM

Answers

All replies

  • I asked the very same question and TomGiam offered a solution which fixed it for me.

    Hope you have the same success.

     

    Here's the link:

     

    http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2571890&SiteID=1

     

    Wednesday, December 19, 2007 4:51 PM
  • Hi ZiggyShort,

    It is a great solution to clone a WPF element by converting it to Xaml and then create a new object from that.

    Unfortunately your link is broken, so here is the current link at the time of writing this: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/0df6181d-938f-4f45-9463-5b5035b57000/

    To anyone interested here is my solution for my current project:

    public static class ExtensionMethods
    {
      public static T XamlClone<T>(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;
      }
    }
    
    This way it simply appears as a method on all objects in your WPF project, you do not need to give any parameters to the method, and it returns an object of the same class as the original.

    Thursday, March 3, 2011 9:21 AM