未检测到已安装的组件.元素已经是另一个元素的子元素

本文关键字:元素 另一个 检测 安装 组件 | 更新日期: 2023-09-27 17:55:04

在App.xaml中,我添加了一个应用程序资源按钮:

 <Application.Resources>
    <Button x:Key="MyButton"/>
</Application.Resources>

MainPage.xaml.cs中,我试图在我的网格中以编程方式添加此按钮。

 Button btn = (Button)Application.Current.Resources["MyButton"];
 myGrid.Children.Add(btn);

但是它给出了这样的错误:

No installed components were detected. Element is already the child of another element.

在MainPage.xaml:

 <Grid x:Name="myGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Grid>

我不知道我做错了什么。

谢谢。

未检测到已安装的组件.元素已经是另一个元素的子元素

如果使用了在应用程序资源中定义的控件的多个实例,通常会抛出此异常。如果是这种情况,您应该这样做:

<Button x:Key="MyButton" x:Shared="false"/>

编辑:似乎WInRT不支持x:shared属性。

有一个解决方法使用ControlTemplates: http://www.gdomc.com/0428/binding-the-content-property-of-a-contentcontrol-in-winrt/

不能添加已经是另一个元素的子元素。就好像你的孩子不能是另一个男人的孩子。