c# - 是否有一种简单/内置的方法来获取 XAML 元素的精确副本(克隆)?

标签 c# wpf xaml clone

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

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

在 PrintReport 中,我将 frameworkelement 打包到其他元素中,以便以与屏幕上略微不同的方式打印它,如下所示:

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 中的原始元素完整地显示在屏幕上?

我想象的是这样的:

FrameworkElement fwe2 = FrameworkElement.Clone(fwe); //pseudo-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 项目中的所有对象上,你不需要给方法任何参数,它返回一个与原始类相同的对象。

关于c# - 是否有一种简单/内置的方法来获取 XAML 元素的精确副本(克隆)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1968625/

相关文章:

c# - Caliburn Micro Datagrid 绑定(bind)

c# - WPF MVVM 防止选项卡更改

c# - WPF:将 List<class> 绑定(bind)到 ComboBox

c# - 如何在 Xamarin.forms xaml 中水平显示 ListView 中的项目?

c# - LINQ 序列化

c# - Android 图片上传到 C# .NET REST 服务

c# - 生成用于在 Visual Studio 2012 中创建 XmlSerializers.dll 的脚本

c# - ViewModel 成员的可见性应该是多少?

c# - 将文件传输到目的地时取消文件传输

c# - 从 MediaElement 控件读取自定义编码的网络流