How to access elements that are embedded inside the ControlTemplate ?

Platform: WPF| Category: ControlTemplates

When you declare elements inside the ControlTemplate, use the ‘Name’ of each control for identifying it from the outside. We can then use the ‘FindName’ function for finding the resource.

An example shown below is for accessing the TextBlock of a button.

[XAML]

<Button Background='LightGoldenrodYellow'>
	<Button.Style>
		<Style TargetType='Button'>
		<!--Set to true to not get any properties from the themes.-->
			<Setter Property='OverridesDefaultStyle' Value='True'/>
			<Setter Property='Template'>
			<Setter.Value>
				<ControlTemplate TargetType='Button'>
				<Grid>
				<Ellipse Name='innerEllipse' Fill='{TemplateBinding Background}'/>
					<ContentPresenter HorizontalAlignment='Center'
                                  			VerticalAlignment='Center'/>
				</Grid>
				</ControlTemplate>
			</Setter.Value>
			</Setter>
		</Style>
	</Button.Style>
</Button>

[C#]
// From inside the custom Button type:
Ellipse ellipse = this.Template.FindName('innerEllipse', this) as Ellipse;

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.