没有检测到安装的组件。该元素已经是另一个元素的子元素。

7
在 App.xaml 中,我添加了一个带有按钮的应用程序资源,如下所示:
 <Application.Resources>
    <Button x:Key="MyButton"/>
</Application.Resources>

MainPage.xaml.cs 中,我尝试在我的网格中以编程方式添加此按钮。
 Button btn = (Button)Application.Current.Resources["MyButton"];
 myGrid.Children.Add(btn);

但是它会出现这样的错误:

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

在MainPage.xaml中:

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

</Grid>

我不知道我做错了什么。
谢谢。
3个回答

3

我尝试了相同的操作,但在app.xaml中出现了错误,错误信息如下:XBF生成中发现语法错误 - Kishor Bikram Oli

0

您不能添加已经是其他元素子元素的元素。这就像您的孩子不能成为另一个人的孩子。


这并不一定是真的。请参见https://www.newscientist.com/article/2107219-exclusive-worlds-first-baby-born-with-new-3-parent-technique/。 - Paymon
1
@Paymon,太棒了。 ;) - Riyas

0
我对这个还不熟悉,但我做了类似的事情,结果犯了同样的错误。 这对我没有起作用。
btn = new Button { Text = $"{i}", HeightRequest = 50, WidthRequest = 50 };
flexLayout1.Children.Add(btn)
flexLayout2.Children.Add(btn)

但这个方法行得通:
flexLayout1.Children.Add(new Button { Text = $"{i}", HeightRequest = 50, WidthRequest = 50 });
flexLayout2.Children.Add(new Button { Text = $"{i}", HeightRequest = 50, WidthRequest = 50 });

欢迎来到Stack Overflow!第二个例子有效是因为C#是按引用传递的。在第一个例子中,您试图两次添加相同的按钮,但在第二个例子中,您每次都创建一个新的按钮。然而,这并没有真正回答OP的问题,因为他试图从资源中构建一个按钮。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接