在 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/
您无法添加已经是另一个元素的子元素的元素。就像你的孩子不可能是另一个男人的孩子一样。
我对此很陌生,但我做了类似的事情并且犯了同样的错误。 这对我不起作用:
btn = new Button { Text = $"{i}", HeightRequest = 50, WidthRequest = 50 };
flexLayout1.Children.Add(btn)
但这有效:
flexLayout1.Children.Add(new Button { Text = $"{i}", HeightRequest = 50, WidthRequest = 50 });