必须首先定义您的UserControl中所需的相关属性:
public partial class MyUserControl : UserControl
{
public Brush LabelBackground
{
get { return (Brush)GetValue(LabelBackgroundProperty); }
set { SetValue(LabelBackgroundProperty, value); }
}
public static readonly DependencyProperty LabelBackgroundProperty =
DependencyProperty.Register("LabelBackground", typeof(Brush), typeof(MyUserControl), new PropertyMetadata(null));
public MyUserControl()
{
InitializeComponent();
}
}
为您的属性值分配给子标签,可以绑定使用绑定的ElementName属性:
<UserControl x:Class="SilverlightApplication1.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
d:DesignHeight="300"
d:DesignWidth="400"
mc:Ignorable="d"
x:Name="UserControl"
>
<Grid x:Name="LayoutRoot">
<sdk:Label x:Name="Title"
HorizontalAlignment="Center"
VerticalAlignment="Center" Content="Title" Background="{Binding LabelBackground, ElementName=UserControl}" />
</Grid>
</UserControl>
当你在使用Silverlight 5,你还可以设置RelativeSource到你的绑定,而不是内部命名你的用户控件:
<sdk:Label Background="{Binding LabelBackground, RelativeSource={RelativeSource AncestorType=UserControl}}" />
然后,使用您的用户控件时,您只需设置(或绑定)的LabelBackground为所需的值:
<local:MyUserControl LabelBackground="Red"/>
只需注意,您也可以创建一个CustomControl而不是UserControl,并以相同的方式向它添加依赖项属性,并且use a TemplateBinding when defining its template。
这不会起作用,因为{绑定LableBG}绑定到标签的DataContext,而不是它的父级UserControl。 –