在我的 Silverlight 4 应用程序中,我想创建一个简单的用户控件,除了其他内容之外,该控件还可以包含另一个控件。我想要的一个例子是边境管制。您可以将任何其他控件(恰好是另一个控件)"放入"边框控件中,以便边框控件包含其他用户控件并显示其内容。创建具有该功能的用户控件需要执行哪些操作?这个想法是将另一个控件放在我的用户控件中的 ContentPresenter 中,如下所示:
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock x:Name="TextBlockHeader" Text="{Binding Title, ElementName=userControl}" HorizontalAlignment="Left" Foreground="White" Margin="5,0"/>
<ContentPresenter x:Name="ContentPresenterObject" Grid.Row="1" />
</Grid>
现在,如何操作才能将子控件(在表达式混合中)添加到我的用户控件,以及如何将其绑定到内容演示器?还是这是一种错误的方法?
提前感谢,
弗兰克
我建议创建一个继承自 ContentControl 的自定义控件。这是一篇很好的博客文章,讨论用户控件和自定义控件
您需要创建一个定义 xaml 的"Generic.xaml",以及一个定义类的 cs 类。
public class CustomControl: ContentControl
{
public CustomControl()
{
this.DefaultStyleKey = typeof(CustomControl);
}
}
您的 xaml 类将如下所示:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyApp">
<Style TargetType="local:CustomControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomControl">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock x:Name="TextBlockHeader" Text="{Binding Title,
ElementName=userControl}" HorizontalAlignment="Left"
Foreground="White" Margin="5,0"/>
<ContentPresenter x:Name="ContentPresenter" Grid.Row="1"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>