How do I, form my contructor in the code-behind get a reference to the OuterBorder control in the XAML below?
<Window Template="{DynamicResource WindowTemplate}">
<Window.Resources>
<ControlTemplate x:Key="WindowTemplate" TargetType="{x:Type Window}">
<AdornerDecorator>
<Border Name="OuterBorder" Background="Black" BorderBrush="Red" BorderThickness="1" CornerRadius="0">
<!-- Implementation here... -->
</Border>
</AdornerDecorator>
</ControlTemplate>
</Window.Resources>
</Window>
How to access elements that are embedded inside the ControlTemplate ? 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.
The ControlTemplate allows you to specify the visual structure of a control. The control author can define the default ControlTemplate and the application author can override the ControlTemplate to reconstruct the visual structure of the control.
Controls in Windows Presentation Foundation (WPF) have a ControlTemplate that contains the visual tree of that control. You can change the structure and appearance of a control by modifying the ControlTemplate of that control.
DataTemplate is about the presentation of data and is one of the many features provided by the WPF styling and templating model. For an introduction of the WPF styling and templating model, such as how to use a Style to set properties on controls, see the Styling and Templating topic.
Two possible solutions:
Solution 1
Put a Loaded event in XAML
<Border Name="OuterBorder" Loaded="Border_Loaded" ...
And in code behind store it in a private field:
private Border border;
void Border_Loaded(object sender, RoutedEventArgs e)
{
this.border = (Border)sender;
}
OR:
Solution 2
Override the OnApplyTemplate of your Window:
private Border border;
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.border = (Border) Template.FindName("OuterBorder", this);
}
You may want to reconsider your approach. What are you trying to do?
Generally, you shouldn't want or need to access portions of the ControlTemplate
from your codebehind because your template is just that-- a template. It's how the control looks. You want your codebehind to generally affect the behavior of the control.
For example, if you're trying to affect the color of the border in the codebehind in certain interactive situations, you really want to add some (pre .Net4) triggers or (post .Net4) a VisualStateManager
to your control template to manage your control's visual states for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With