我猜这可能是我在某个地方犯的一个容易犯的错误。我有一个自定义控件,根据基础知识:
<local:CustomUserControl x:Class="Test.UI.CustomUserControl"
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"
xmlns:local="clr-namespace:Test.UI"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
IsEnabled="True" Loaded="CustomUserControl_Loaded">
<!-- Main border -->
<Border BorderBrush="#9B000000" BorderThickness="1" Margin="0,0,0,0" Padding="0">
<Grid Margin="0" Name="outerGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Margin="0" Grid.Row="0" Grid.Column="0" Name="innerGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<!-- Backgound -->
<Rectangle Fill="#FF5B87B8" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Name="headerRectangle" PreviewMouseLeftButtonUp ="headerRectangle_MouseLeftButtonUp" />
<!-- Text -->
<Label Grid.Row="0" Grid.Column="0" HorizontalContentAlignment="Left" VerticalContentAlignment="Center" Name="HeaderLabel" Content="Hello" Margin="5,0,0,0" Foreground="White" FontSize="18" Background="#FF5B87B8" PreviewMouseLeftButtonUp ="HeaderLabel_MouseLeftButtonUp" />
</Grid>
<!-- Content -->
<ContentPresenter Name="MainContent" Grid.Row="1" Grid.Column="0" Content="{Binding Content}" />
</Grid>
</Border>
</local:CustomUserControl>
当在表单上显示时,如下所示,它会绘制一个带有阴影顶部的框,带有白色文本:
<ui:CustomUserControl Grid.Row="0" Grid.Column="2" Name="borderDiagram" Header="Hello" />
但是,如果我尝试向ContentPresenter添加内容:
<ui:CustomUserControl Grid.Row="0" Grid.Column="2" Name="borderDiagram" Header="Hello">
<Label Content="Um..." />
</ui:CustomUserControl >
它会覆盖整个自定义控件,只留下“嗯...”。标签
我认为在设置内容时我设法覆盖整个控件,那么如何确保它是内容的ContentPresenter,而不是父控件呢?
答案 0 :(得分:1)
CustomUserControl有一些默认内容:
<!-- Main border -->
<Border> ...
</Border>
并且内容已替换为<Label Content="Um..." />
使其按预期工作(ContentPresenter中显示的标签),您应该定义默认模板:
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<Border BorderBrush="#9B000000" BorderThickness="1" Margin="0,0,0,0" Padding="0">
<Grid Margin="0" Name="outerGrid">
...
<!-- Content -->
<ContentPresenter Name="MainContent" Grid.Row="1" Grid.Column="0"
Content="{TemplateBinding Content}" />
</Grid>
</Border>
</ControlTemplate>
</UserControl.Template>
注意一个重要的变化:
Content="{TemplateBinding Content}"
ContentPresenter使用模板绑定来获取和显示自定义内容