gpt4 book ai didi

c# - 如何在 WinRT XAML C# 中克隆 UIElement?

转载 作者:太空狗 更新时间:2023-10-29 21:45:25 25 4
gpt4 key购买 nike

我首先尝试过这种方法,但出现错误“元素已经是另一个元素的子元素”

var objClone = new MyImageControl();
objClone = this;
((Canvas)this.Parent).Children.Add(objClone);

然后我查了thisthis ,但 XamlWriter 和 XamlReader 在 WinRT 中不可用。我试过使用 MemberwiseClone()但它抛出异常,“无法使用与其底层 RCW 分离的 COM 对象。System.Runtime.InteropServices.InvalidComObjectException”。那么谁能告诉我如何将 Canvas 中的现有 UserControl 克隆到自身?

最佳答案

我编写了一个 UIElement 扩展,用于复制元素的属性和子元素——请注意,它为克隆设置事件。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using System.Reflection;
using Windows.UI.Xaml.Controls;

namespace UIElementClone
{
public static class UIElementExtensions
{
public static T DeepClone<T>(this T source) where T : UIElement
{

T result;

// Get the type
Type type = source.GetType();

// Create an instance
result = Activator.CreateInstance(type) as T;

CopyProperties<T>(source, result, type);

DeepCopyChildren<T>(source, result);

return result;
}

private static void DeepCopyChildren<T>(T source, T result) where T : UIElement
{
// Deep copy children.
Panel sourcePanel = source as Panel;
if (sourcePanel != null)
{
Panel resultPanel = result as Panel;
if (resultPanel != null)
{
foreach (UIElement child in sourcePanel.Children)
{
// RECURSION!
UIElement childClone = DeepClone(child);
resultPanel.Children.Add(childClone);
}
}
}
}

private static void CopyProperties<T>(T source, T result, Type type) where T : UIElement
{
// Copy all properties.

IEnumerable<PropertyInfo> properties = type.GetRuntimeProperties();

foreach (var property in properties)
{
if (property.Name != "Name") // do not copy names or we cannot add the clone to the same parent as the original.
{
if ((property.CanWrite) && (property.CanRead))
{
object sourceProperty = property.GetValue(source);

UIElement element = sourceProperty as UIElement;
if (element != null)
{
UIElement propertyClone = element.DeepClone();
property.SetValue(result, propertyClone);
}
else
{
try
{
property.SetValue(result, sourceProperty);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
}
}
}
}
}
}
}

如果您觉得有用,请随意使用此代码。

关于c# - 如何在 WinRT XAML C# 中克隆 UIElement?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15564493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com