Mr.Sheep
Mr.Sheep

Reputation: 311

Bind element inside of datatemplate to parent's property

how can i bind an element inside of a template to a property of its parent like:

<Button Tag="rofl">
   <Button.ContentTemplate>
      <DataTemplate>
         <TextBlock Text="{ HERE I WANT TO BIND TO THE BUTTONS TAG }"/>
      </DataTemplate>
   </Button.ContentTemplate>
</Button>

Is that possible?

Upvotes: 1

Views: 1540

Answers (2)

Andr&#233; B
Andr&#233; B

Reputation: 1709

In addition to @Pedro Lamas's answer you can also perform this by the following way:

        <Button x:Name="ButtonTemplate" Tag="rofl">
            <Button.ContentTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Tag, ElementName=ButtonTemplate}"/>
                </DataTemplate>
            </Button.ContentTemplate>
        </Button>

You define a name for your control and access it's property in it's DataTemplate thanks to the ElementName feature.

Upvotes: 3

Pedro Lamas
Pedro Lamas

Reputation: 7233

You should be able to use a RelativeSource with the TemplatedParent to do that:

<TextBlock Text="{Binding Tag, RelativeSource={RelativeSource TemplatedParent}"/>

Upvotes: 1

Related Questions