对 ControlTemplate 内的控件的引用
如何在代码隐藏中形成构造函数来获取对下面 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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两种可能的解决方案:
解决方案 1
将 Loaded 事件放入 XAML 中
,并在后面的代码中将其存储在私有字段中:
或者:
解决方案 2
覆盖窗口的 OnApplyTemplate:
Two possible solutions:
Solution 1
Put a Loaded event in XAML
And in code behind store it in a private field:
OR:
Solution 2
Override the OnApplyTemplate of your Window:
您可能需要重新考虑您的方法。你想做什么?
一般来说,您不应该希望或不需要从代码隐藏中访问
ControlTemplate
的部分,因为您的模板只是一个模板。这就是控件的外观。您希望您的代码隐藏总体上影响控件的行为。例如,如果您试图在某些交互情况下影响代码隐藏中的边框颜色,您确实需要添加一些(.Net4 之前的)触发器或(.Net4 之后的)一个
VisualStateManager
到您的控件模板来为您管理控件的视觉状态。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.