1

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.

Jerry Nixon
  • 31,313
  • 14
  • 117
  • 233
  • In silverlight, binding to custom attached property is a problem however I have read somewhere that you can try putting entire name of attached property in round brackets and see if it works or not – Akash Kava Aug 10 '11 at 18:29
  • I wish that worked; tried `(local:MyButtonThing).Text2` but no. – Jerry Nixon Aug 10 '11 at 19:35

2 Answers2

1

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

{Binding RelativeSource={RelativeSource AncestorType=Button},
         Path=(local:MyButtonThing.Text2)}
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Well, that's perfect. But, could you explain why it is so obvious? There's clearly something I do not understand. Why doesn't Self work? – Jerry Nixon Aug 10 '11 at 23:53
  • 1
    @JerryNixon: Self points towards the TextBlock, the propety you want to bind to is not set on that TextBlock but the Button which contains the TextBlock. Besides that you need the parentheses around the property to indicate that you bind to an attached property (obviously this is an attached property). – H.B. Aug 11 '11 at 00:39
0

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

Jerry Nixon
  • 31,313
  • 14
  • 117
  • 233
Rachel
  • 130,264
  • 66
  • 304
  • 490