简体   繁体   English

在ControlTemplate中引用控件

[英]Reference to control inside a ControlTemplate

How do I, form my contructor in the code-behind get a reference to the OuterBorder control in the XAML below? 我如何在代码隐藏中形成我的构造函数,在下面的XAML中获取对OuterBorder控件的引用?

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

Two possible solutions: 两种可能的解决方

Solution 1 解决方案1

Put a Loaded event in XAML 在XAML中放置一个Loaded事件

<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 解决方案2

Override the OnApplyTemplate of your Window: 覆盖窗口的OnApplyTemplate:

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. 通常,您不应该或不需要从代码隐藏中访问ControlTemplate部分内容,因为您的模板就是 - 模板。 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. 例如,如果您试图在某些交互情况下影响代码隐藏中边框的颜色,您真的想要将一些(pre .Net4)触发器或(发布.Net4) VisualStateManager到您的控件模板来管理您的控制的视觉状态为你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM