是否有一种简单/内置的方法来获取 XAML 元素的精确副本(克隆)? [英] Is there an easy/built-in way to get an exact copy (clone) of a XAML element?

查看:26
本文介绍了是否有一种简单/内置的方法来获取 XAML 元素的精确副本(克隆)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使 XAML 区域可打印,因此必须使这个按钮处理程序:

I need to make areas of XAML printable and so have make this button handler:

private void Button_Click_Print(object sender, RoutedEventArgs e)
{
    Customer.PrintReport(PrintableArea);
}

在 PrintReport 中,我将框架元素打包到其他元素中,以便以与在屏幕上略有不同的方式打印出来,如下所示:

And in PrintReport I pack the frameworkelement into other elements in order to print it in a slightly different way than it is on the screen, like this:

public void PrintReport(FrameworkElement fwe)
{
    StackPanel sp = new StackPanel();
    sp.Children.Add(fwe);
    TextBlock tb = new TextBlock();
    tb.Text = "hello";
    sp.Children.Add(tb);

    PrintDialog dialog = new PrintDialog();
    if (dialog.ShowDialog() == true)
    { 
        dialog.PrintVisual(sp, "Print job"); 
    }
}

但是上面给了我以下错误:

指定的元素已经是另一个元素的逻辑子元素.先断开连接.

Specified element is already the logical child of another element. Disconnect it first.

是否有一种简单的方法可以克隆 FrameworkElement,以便我可以操作副本、打印它,然后忘记它,而将 XAML 中的原始元素完整地显示在屏幕上?

我可以想象这样的事情:

Something like this I would imagine:

FrameworkElement fwe2 = FrameworkElement.Clone(fwe); //pseudo-code

推荐答案

我在当前项目中遇到了类似的问题,并使用此代码解决了.

I had a similar problem in my current project and solved it with this code.

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

这样它就简单地显示为 WPF 项目中所有对象的一个​​方法,您不需要为该方法提供任何参数,它返回一个与原始类相同的对象.

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.

这篇关于是否有一种简单/内置的方法来获取 XAML 元素的精确副本(克隆)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆