How is TemplateBinding working in UserControl Template?

11,839

According to TemplateBinding to DependencyProperty on a custom control is not working, TemplateBinding does not work for custom dependency properties on controls.

As a solution it is suggested to use

{Binding MyProperty, RelativeSource={RelativeSource TemplatedParent}}

Share:
11,839
winterTTr
Author by

winterTTr

Enjoying coding SDE at Microsoft Focus on programming tech on C++ Like functional programming with Common lisp like Python, Emacs Author of AceJump minor mode on Emacs Contact me: winterTTr

Updated on June 04, 2022

Comments

  • winterTTr
    winterTTr almost 2 years

    I am new one to create UserControl and now I am trying to customize the UserControl Template as below:

    <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>
    

    At the same time I have create the dependencyproperty in back-end code:

    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));
        ......
    

    I want to use TemplateBinding in XAML to bind Fill property of my PieButton to fill the path object. The Visual Studio Designer warns me that "the Fill property is not accessible or recognized".

    Based on my understanding, the TemplateBinding find the property name from the element that apply this ControlTemplate, which should be PieControl here, but why the Fill Property cannot access here?

    BTW,

    I test the following binding, and it can work for me

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

    But I still think the TemplateBinding should be able to work under this scenario, so please point out my fault here. Thanks.