Jerry Nixon
Jerry Nixon

Reputation: 31803

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.

Upvotes: 1

Views: 503

Answers (2)

brunnerh
brunnerh

Reputation: 184296

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

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

Upvotes: 1

Rachel
Rachel

Reputation: 132548

You are binding to the DataContext of TextBox, which doesn't have a Text2 property

Use this instead:

<TextBlock Text="{Binding RelativeSource={RelativeSource Self},
                   Path=local:MyButtonThing.Text2}" />

It sets the TextBox's DataContext to the TextBox Control, not the TextBox's DataContext

Upvotes: 0

Related Questions