C# 如何允许UserControl中有多个子项?
我有以下用户控件:C# 如何允许UserControl中有多个子项?,c#,wpf,user-controls,dockpanel,C#,Wpf,User Controls,Dockpanel,我有以下用户控件: <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Label Grid.Row="0" Content="USER CONTROL" HorizontalAlignment="Stretch"
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="USER CONTROL" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" Name="label1"
VerticalAlignment="Top" FontSize="26" Padding="0"/>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<Border BorderBrush="Black" BorderThickness="1">
<DockPanel x:Name="dPanel" Background="White">
</DockPanel>
</Border>
</ScrollViewer>
</Grid>
当我在MainWindow.XAML中使用以下XAML时:
<local:UserDockPanel>
<Label ...>
<Label ...>
</local:UserDockPanel>
上面说我不能有一个以上的孩子
我的第一个问题是:我应该使用UserControl还是使用自定义控件?
我认为UserControl最适合我的情况,在我的DockPanel上有一个标签、边框和Scrollviewer
而且,据我所知,面板不能模板化。它看起来不太好看,因此没有风格
第二个问题:如果我应该使用UserControl,我如何使它允许将多个子项添加到dock panel中?您可以使用
ItemsControl来实现这一点,无需对任何内容进行子类化或创建自己的子项:
<Window x:Class="WpfApplication4.Window16"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window16" Height="300" Width="300">
<Window.Resources>
<Style TargetType="ItemsControl" x:Key="UserDockPanelStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ItemsControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="USER CONTROL" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" Name="label1"
VerticalAlignment="Top" FontSize="26" Padding="0"/>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
<Border BorderBrush="Black" BorderThickness="1">
<ItemsPresenter/>
</Border>
</ScrollViewer>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<DockPanel IsItemsHost="True" Background="White"/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<ItemsControl Style="{StaticResource UserDockPanelStyle}">
<Label DockPanel.Dock="Bottom" Content="Bottom"/>
<Label DockPanel.Dock="Top" Content="Top"/>
<Border Background="Blue"/>
</ItemsControl>
</Window>
这太完美了!我能帮你解释一下这里发生了什么吗?我理解其中的一些,但是,我真的很想知道它是如何工作的。您正在为ItemsControl
创建一个自定义ControlTemplate
,然后将其ItemsPanelTemplate
设置为DockPanel
。