【发布时间】:2016-09-03 16:56:12
【问题描述】:
我想在 Xaml 中创建 Control,但是我可以使用 C# 代码创建这个 Control,但不知何故它太冗长了。
所以我在Page.Resources 中用x:Name="UserControl" 声明这个Control。
在运行时,我会将这个UserControl 附加到Grid。
Page.xaml:
<Page Loaded="OnLoaded">
<Page.Resources>
<UserControl x:Name="UserControl">
<TextBlock>Hi, There</TextBlock>
</UserControl>
</Page.Resources>
<Grid x:Name="Grid">
</Grid>
</Page>
Page.xaml.cs
private void OnLoaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
Grid.Children.Add(UserControl); // exception
}
运行此程序时,我收到了 COMException 和消息:WinRT information: Element is already the child of another element。
我检查UserControl中的属性Parent为空,怎么会发生这种异常?
如何在 XAML 中声明 Control 而不将其添加到 Visual Tree 中?
【问题讨论】: