我敢肯定这是一个真正的初学者问题;我只是无法弄清楚如何搜索它。
我有一个简单的 UserControl (MyNewControl),它只有三个控件,其中一个是以下标签:
<sdk:Label x:Name="Title" />
然后,在另一个控件中,我想使用 MyNewControl,如下所示:
<local:MyNewControl Grid.Column="1" x:Name="MyNewGuy" />
例如,我需要做什么才能使第二个控件可以为我的标题标签设置渐变背景?
我敢肯定这是一个真正的初学者问题;我只是无法弄清楚如何搜索它。
我有一个简单的 UserControl (MyNewControl),它只有三个控件,其中一个是以下标签:
<sdk:Label x:Name="Title" />
然后,在另一个控件中,我想使用 MyNewControl,如下所示:
<local:MyNewControl Grid.Column="1" x:Name="MyNewGuy" />
例如,我需要做什么才能使第二个控件可以为我的标题标签设置渐变背景?
首先,您在 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设置为您的绑定,而不是在内部命名您的 UserControl:
<sdk:Label Background="{Binding LabelBackground, RelativeSource={RelativeSource AncestorType=UserControl}}" />
然后,在使用您的 UserControl 时,您只需将 LabelBackground 设置(或绑定)为所需的值:
<local:MyUserControl LabelBackground="Red"/>
请注意,您还可以创建CustomControl而不是 UserControl,以相同的方式向其添加依赖属性,并在定义其模板时使用 TemplateBinding。
您可以使用自定义控件中的依赖属性来做到这一点。假设您将 LableBG 定义为自定义控件中的依赖属性,并与您在 xaml 中定义的 Label 控件的背景进行绑定。当您在另一个控件中使用自定义控件时,您可以从 xaml 或从后面的代码设置它的 LableBG。
注意:您定义的依赖属性的类型应该是 Brush
例如:
在自定义控件的 cs 文件中定义依赖属性:
/1. Declare the dependency property as static, readonly field in your class.
public static readonly DependencyProperty LableBGProperty = DependencyProperty.Register(
"LableBG", //Property name
typeof(Brush), //Property type
typeof(MySilverlightControl), //Type of the dependency property provider
null );//Callback invoked on property value has changes
<sdk:Label x:Name="Title" Background="{Binding LableBG }" /> (Custom Control)
<local:MyNewControl Grid.Column="1" x:Name="MyNewGuy" LableBG="Red" /> (Another control)