如何在WPF中克隆Canvas

时间:2016-04-22 21:15:45

标签: wpf wpf-controls drawing

美好的一天。我尝试创建图形编辑器(如Paint)。所以,我需要创建“撤消”和“重做”按钮。如果我复制儿童帆布,那么Canvas.Children包含很多项目需要花费太多时间。如何实现撤消和重做操作?

1 个答案:

答案 0 :(得分:1)

我从未使用Canvas但是为了克隆它我试过这个并且似乎有效:

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;
}