Search code examples
wpfcontroltemplateattached-properties

Problem reading AttachedProperty in ControlTemplate


This is my attached property:

public class MyButtonThing
{
    public static string GetText2(DependencyObject obj)
    {
        return (string)obj.GetValue(Text2Property);
    }
    public static void SetText2(DependencyObject obj, string value)
    {
        obj.SetValue(Text2Property, value);
    }
    public static readonly DependencyProperty Text2Property =
        DependencyProperty.RegisterAttached("Text2", 
        typeof(string), typeof(System.Windows.Controls.Button));
}

This is my ControlTemplate:

EDIT this will work fine:

<Window.Resources>
    <ControlTemplate TargetType="{x:Type Button}" 
                     x:Key="MyButtonTemplate">
        <Border>
            <DockPanel LastChildFill="True">
                <TextBlock Text="{TemplateBinding Content}" 
                           DockPanel.Dock="Top"/>
                <TextBlock Text={Binding RelativeSource={RelativeSource
                          AncestorType=Button},
                          Path=(local:MyButtonThing.Text2)}"  />
            </DockPanel>
        </Border>
    </ControlTemplate>
</Window.Resources>

<Button Template="{StaticResource MyButtonTemplate}" 
        local:MyButtonThing.Text2="Where's Waldo"
        >Hello World</Button>

My problem? Text2 renders properly in the Desginer, not at runtime.


Solution

  • You set the value on the button, and it is attached, hence:

    {Binding RelativeSource={RelativeSource AncestorType=Button},
             Path=(local:MyButtonThing.Text2)}