我有以下用户控件:
<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上的Border和Scrollviewer。
另外,根据我的理解,Panel不能模板化。它看起来很少,因此没有风格。
第二个问题:如果我应该使用UserControl,我怎样才能这样做,以便允许将多个孩子添加到停靠面板?
答案 0 :(得分:1)
您可以使用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>