Элемент уже является потомком другого элемента. '
Каждый элемент пользовательского интерфейса в UWP может использоваться в пользовательском интерфейсе только в одном месте одновременно. Экземпляр будет создан при загрузке ресурса. Таким образом, вы больше не можете добавлять их на панель. Однако вы можете создать глубокую копию с помощью команды UIElementExtensions
и добавить копию на панель.
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")
{
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);
}
}
}
}
}
}
}
Использование
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
var border = Resources["Border"] as Border;
if (!(Content is Panel panel)) return;
var NewBorder = border.DeepClone<Border>();
panel.Children.Add(NewBorder);
}