我创建了一个UserControl。我想用这段代码包含它:
<UserControl1 Header="Heading">
<TextBlock Text="My Content" />
</UserControl1>
那是UserControl:
<UserControl x:Class="WpfApplication1.UserControl1"
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" MinHeight="200"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<Style TargetType="ToggleButton">
<!-- ... -->
</Style>
</UserControl.Resources>
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Path=Header}" Grid.Column="0" />
<ToggleButton Name="ToggleButton" IsChecked="True" Grid.Column="2" />
</Grid>
<Rectangle Stroke="#c3c3c3" StrokeThickness="1" Height="1" StrokeDashArray="4 4" SnapsToDevicePixels="True" Focusable="False" />
<!-- Content -->
<ContentControl>
<ContentPresenter/>
</ContentControl>
</StackPanel>
</UserControl>
现在我的问题:
如果我将它与以下代码集成,
<UserControl1 Header="Heading">
<TextBlock Text="My Content" />
</UserControl1>
我收到的结果是:
这不是我想要的。
但是当我将它与此代码集成时,我得到了理想的结果。
<UserControls:UserControl1 Header="Heading" />
我第一次走错了什么?
答案 0 :(得分:6)
为了让事情按预期运行,您必须设置UserControl的Template
:
<UserControl x:Class="UserCtrl.UserControl1"
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">
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding Path=Header,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType=UserControl}}}" />
<ToggleButton Name="ToggleButton" IsChecked="True" Grid.Column="2" />
</Grid>
<Rectangle Stroke="#c3c3c3" StrokeThickness="1" Height="1" StrokeDashArray="4 4" SnapsToDevicePixels="True" Focusable="False" />
<!-- Content -->
<ContentPresenter/>
</StackPanel>
</ControlTemplate>
</UserControl.Template>
<!-- Initial Content of the UserControl -->
<TextBlock Text="Initial Content"/>
</UserControl>
答案 1 :(得分:0)
第一种方式没有错误。它只是创建UserControl1
并将内容设置为TextBlock
,从而覆盖您在定义中设置的内容。第二种方式创建UserControl1
并按原样保留内容。