通用用户控件:
XAML:
<UserControl x:Class="WpfControlLibrary.GenericUserControl"
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:WpfControlLibrary"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" x:Name="Control">
<UserControl.Resources>
<Style TargetType="{x:Type local:GenericUserControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:GenericUserControl}">
<Grid Background="{Binding Background, ElementName=Control}">
<Grid.RowDefinitions>
<RowDefinition Height="5"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="5"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="5"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Title, ElementName=Control}"/>
<ContentPresenter Grid.Column="1" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
后面的代码:
namespace WpfControlLibrary
{
public partial class GenericUserControl
{
public string Title
{
get { return (string)GetValue(TitleProperty); }
set { SetValue(TitleProperty, value); }
}
public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title", typeof(string), typeof(GenericUserControl), new PropertyMetadata(string.Empty));
public GenericUserControl()
{
InitializeComponent();
}
}
}
而不是像这样使用用户控件:
<wpfControlLibrary:GenericUserControl Title="Other Title" Background="LightGray">
<wpfControlLibrary:GenericUserControl Title="Yet Another Title" Background="Gray"/>
</wpfControlLibrary:GenericUserControl>