如何在自定义模板中使用自定义属性?

时间:2011-10-14 15:14:20

标签: c# silverlight xaml wpf-controls

假设想要创建一个左侧有一个小椭圆的自定义按钮。 我希望这个椭圆的颜色是数据可绑定的。

所以我点了Blend并在表面上放了一个按钮Edit a Copy of the Template。 我现在有了自定义模板,我在其中放了一个小的Ellipse

...

<Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="White" CornerRadius="3">
  <Grid Background="{TemplateBinding Background}" Margin="1">
    <snip   />

    <!-- My ellipse here -->
    <Ellipse x:Name="ellipse" Width="10" Height="10" HorizontalAlignment="Left" />
  </Grid>
</Border>

...

我右键单击此按钮并选择名为Make into UserControl的{​​{1}}。 在此按钮后面的代码中,我添加了自定义MyButton画笔:

dependency property for the

然后我可以使用我的自定义按钮:

public Brush MyColor
{
  get { return (Brush)GetValue(MyColorProperty); }
  set { SetValue(MyColorProperty, value); }
}

public static readonly DependencyProperty MyColorProperty = DependencyProperty.Register("MyColor", typeof(Brush), typeof(MyButton), new PropertyMetadata(new opertyChangedCallback(MyColorPropertyChanged)));

private static void MyColorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  var thisControl = d as MyButton;
}

但后来我被困住了。如何将我的椭圆颜色(上面的x:Name =“ellipse”)绑定到我的<local:MyButton Width="130" MyColor="Red"/> 属性?

编辑:所以我使用MyColor绑定用户控件中的Fill属性,但后来我得到Fill={TemplateBinding MyColor}。 好的,所以我需要将我的模板定位到自定义MyButton类型,但我该怎么做呢? 我可以简单地将Button更改为MyButton,因为我得到了Property MyColor was not found in type Button

Property 'ContentTemplate' was not found in type 'MyButton'

2 个答案:

答案 0 :(得分:1)

好的,首先,你的MyButton控件应该有一个DependencyProperty,比如说,MyColor - 你有吗?在模板中,您应该使用TemplateBinding绑定到该属性。在使用您的控件的XAML中,您可以像使用它一样使用它:<local:MyButton Width="130" MyColor="Red"/>

您的模板似乎缺少模板绑定:

<Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}"...>
    <Grid Background="{TemplateBinding Background}" Margin="1">
        ...
        <Ellipse x:Name="ellipse" Width="10" Height="10" HorizontalAlignment="Left"
                 Fill="{TemplateBinding MyColor}" />
    </Grid>
</Border>

顺便说一下,MyColor应该是Brush,而不仅仅是Color

答案 1 :(得分:1)

这里的问题是UserControl不是您控制的正确基础。你应该创建一个模板控件。

在Visual Studio中,将新的“Silverlight模板化控件”添加到名为MyButton的项目中。

打开MyButton.cs并将其基类更改为Button。将MyColor依赖项属性放入代码中。

打开Themes / Generic.xaml,找到为此新MyButton控件放置的默认样式。用您的模板替换该样式中的Template。现在,模板中的Fill="{TemplateBinding MyColor}"将起作用。