2012-12-13 57 views
0

我确定这是一个真正的初学者问题;我只是无法找出如何搜索它。Silverlight如何创建可自定义属性的usercontrol

我有一个简单的用户控件(MyNewControl)仅具有三个控件,其中一个是以下标签:

<sdk:Label x:Name="Title" /> 

在另一个控制,那么,我想用MyNewControl,像这样:

<local:MyNewControl Grid.Column="1" x:Name="MyNewGuy" /> 

我需要做什么以便第二个控件可以为我的标题标签设置渐变背景?

回答

1

必须首先定义您的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

0

您可以在自定义控件中使用dependency property。假设您将LableBG定义为自定义控件中的依赖项属性,并使用xaml中已定义的Label控件的背景进行绑定。当你在另一个控件中使用你的自定义控件时,你可以从xaml或其他代码中设置它的LableBG。

注意:您定义的依赖项属性的类型应该是刷

的对于如:

定义依赖项属性在您的自定义控件的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) 
+0

这不会起作用,因为{绑定LableBG}绑定到标签的DataContext,而不是它的父级UserControl。 –

相关问题