How to bind ControlTemplate's child property to other element with xaml?

Anonymous
2021-03-09T04:05:17.73+00:00

Here i have a control template which has label as its child.
Now i want to get properties of that label like text or width.
How to achieve this with xaml?

<ControlTemplate>
 <Label
 x:Name="MyLabel"
 Text="This Is a Button"
 />
 </ControlTemplate>



 <Button
 Text="{Binding Source={x:Reference MyLabel}, Path=Text}" />
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,296 questions
Universal Windows Platform (UWP)
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,676 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
766 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Mouad Cherkaoui 6 Reputation points
    2021-03-09T07:19:11.41+00:00

    Hi,

    you can use the ControlTemplate as resource and make it specific for a certain type, and referencing it as template for your Buttons, Grids, or any UIElement, lets take a look to your example refactored:

    <Page.Resources>
        <ControlTemplate x:Key="controlTemplate" TargetType="Button">
            <Border Background="{TemplateBinding Background}">
                <Label
                  x:Name="MyLabel"
                  Content="{TemplateBinding Content}"/>
    
            </Border>
        </ControlTemplate>
    </Page.Resources>
    <Grid>
        <Button
            Template="{StaticResource controlTemplate}" Content="Click!" Background="Gray"/>
    </Grid>
    

    here we are using the control template as template for the Button through its Template property, and in the other hand the ControlTemplate have its property Content bound to its consumer control which means that the Content of the button is bound to the Content property of label in the control template, which is done using the TemplateBinding expression, also the background of the property is bound to the background of the border in the control template.

    Hope it helps!

    0 comments No comments