views:

39

answers:

2

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>
A: 

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);
}
Arcturus
Your solution no. 2 did the job for me. Thanks!
kennethkryger
+1  A: 

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.

Greg D
I agree this would be the "by-the-book" way doing it. However, I have to create a adorner in the code-behind and setup a binding to this, so here "Acturus's" solution no. 2 was the right (and fastest) way of accomplishing this.
kennethkryger