我需要使 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/