问题
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.
回答1:
You set the value on the button, and it is attached, hence:
{Binding RelativeSource={RelativeSource AncestorType=Button},
         Path=(local:MyButtonThing.Text2)}
回答2:
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
来源:https://stackoverflow.com/questions/7014924/problem-reading-attachedproperty-in-controltemplate