Evgeniy175
Evgeniy175

Reputation: 334

How to clone Canvas in WPF

Good day. I try to create graphic editor (like Paint). So, i need to create "Undo" and "Redo" buttons. If i copy Childrens of canvas, it takes too much time when Canvas.Children consists many items. How to implement Undo and Redo actions?

Upvotes: 1

Views: 1411

Answers (1)

Pollitzer
Pollitzer

Reputation: 1620

I never used Canvas but to clone it I tried this and it seems to work:

Canvas canvas = new Canvas();
canvas.Background = Brushes.Thistle;

Canvas clonedCanvas = ElementClone<Canvas>(canvas);
Brush clonedBrush = clonedCanvas.Background;

/// <summary>
/// Clones an element.
/// </summary>
public static T ElementClone<T>(T element)
{
    T clone = default(T);
    MemoryStream memStream = ElementToStream(element);
    clone = ElementFromStream<T>(memStream);
    return clone;
}

/// <summary>
/// Saves an element as MemoryStream.
/// </summary>
public static MemoryStream ElementToStream(object element)
{
    MemoryStream memStream = new MemoryStream();
    XamlWriter.Save(element, memStream);
    return memStream;
}

/// <summary>
/// Rebuilds an element from a MemoryStream.
/// </summary>
public static T ElementFromStream<T>(MemoryStream elementAsStream)
{
    object reconstructedElement = null;

    if (elementAsStream.CanRead)
    {
        elementAsStream.Seek(0, SeekOrigin.Begin);
        reconstructedElement = XamlReader.Load(elementAsStream);
        elementAsStream.Close();
    }

    return (T)reconstructedElement;
}

Upvotes: 1

Related Questions