我在Container.xaml中有以下代码:
<UserControl x:Class="WpfLibraries.Container"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Border x:Name="Group" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" CornerRadius="20" Background="White">
<StackPanel Orientation="Vertical" Margin="5,0,5,5">
<Border BorderBrush="Black" CornerRadius="10" HorizontalAlignment="Center" VerticalAlignment="Top" Width="auto" Height="auto" Background="{Binding Background, ElementName=Group}" BorderThickness="{Binding BorderThickness, ElementName=Group}" Margin="0,-20,0,0" >
<TextBlock VerticalAlignment="Center" Text="Group" FontSize="20" Margin="5"/>
</Border>
<StackPanel x:Name="ContentPanel" Orientation="Horizontal" Margin="0,10,0,0"/>
</StackPanel>
</Border>
我想将嵌套类型放在Stack面板“ContentPanel”中,如下所示:
<local:Container HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<local:Container.ContentPanel>
<!--More controls will be placed here-->
</local:Container.ContentPanel>
</local:Container>
答案 0 :(得分:1)
目前还不完全清楚你在这里想要达到的效果。但是,如果我理解正确,您只是希望能够将子项添加到名为UserControl
的{{1}}自己的StackPanel
,但是要使用"ContentPanel"
的客户端代码1}}。
如果这是正确的,那么实现此目的的最简单方法就是在UserControl
中公开StackPanel
Children
属性:
UserControl
然后,当您想要在客户端XAML中向子面板添加子项时,您可以执行以下操作:
class Container : UserControl
{
public UIElementCollection ContentPanelChildren
{
get { return this.ContentPanel.Children; }
}
...
}
当然,请注意,公共属性的名称必须与<local:Container HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<local:Container.ContentPanelChildren>
<TextBlock Text="Sample child content"/>
<TextBlock Text="Other sample child content"/>
</local:Container.ContentPanelChildren>
</local:Container>
为x:Name
元素生成的私有字段的名称不同。您无法将它们命名为StackPanel
。
如果这不能解决您的实际问题,请更具体。提供一个好的Minimal, Complete, and Verifiable example,清楚地显示您正在尝试完成的内容,并详细说明该代码的功能以及您希望它做什么。
答案 1 :(得分:0)
从逻辑上讲,我认为你不能这样做。你正在那里创建一个无限循环。因为你拥有的每个Container
对象,都会有一个子Container
对象。同一个孩子Container
对象肯定也会有一个孩子Container
。将其转换为纯代码,它几乎类似于写这个:
public void MyFunction()
{
this.MyFunction();
}
你打电话给MyFunction()
一次,你的程序将无休止地循环。