TemplateBinding如何在UserControl模板中工作?

时间:2013-02-20 07:10:23

标签: wpf xaml user-controls controltemplate templatebinding

我是新创建UserControl的人,现在我正在尝试自定义UserControl模板,如下所示:

<UserControl x:Class="WpfApplication1.PieButton"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Loaded="OnLoaded">
    <UserControl.Template>
        <ControlTemplate>
            <Path Name="path" Stroke="Aqua" StrokeThickness="3">
                <Path.Fill>
                    <SolidColorBrush Color="{TemplateBinding Fill}" />
                </Path.Fill>
                <Path.Data>
                ......
</UserControl>

同时我在后端代码中创建了dependencyproperty:

public partial class PieButton : UserControl
{
    public PieButton()
    {
        InitializeComponent();
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {

    }



    public Color Fill
    {
        get { return (Color)GetValue(FillProperty); }
        set { SetValue(FillProperty, value); }
    }

    public static readonly DependencyProperty FillProperty =
        DependencyProperty.Register("Fill", typeof(Color), typeof(PieButton));
    ......

我想在XAML中使用TemplateBinding绑定我的PieButton的Fill属性来填充路径对象。 Visual Studio Designer警告我“无法访问或识别”填充属性“。

根据我的理解,TemplateBinding从应用此ControlTemplate的元素中找到属性名称,此处应为PieControl,但为什么Fill属性无法在此处访问?< / p>

顺便说一句,

我测试了以下绑定,它可以为我工作

Color="Binding Fill,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type UserControl}}"

但我仍然认为TemplateBinding应该可以在这种情况下工作,所以请在这里指出我的错。感谢。

1 个答案:

答案 0 :(得分:18)

根据TemplateBinding to DependencyProperty on a custom control is not working, TemplateBinding不适用于控件上的自定义依赖项属性。

作为解决方案,建议使用

{Binding MyProperty, RelativeSource={RelativeSource TemplatedParent}}

相关问题