问题描述
我想在 UWP 应用程序中使用 C# 向 ControlTemplate 添加网格
I want add grid to ControlTemplate using C# in UWP application
例如我有如下 XAML 代码:
For example I have XAML code like:
<ControlTemplate TargetType="HyperlinkButton">
<Grid Name="RootGrid">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal"/>
<VisualState Name="PointerOver">
<Storyboard>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentPresenter Name="ContentPresenter" AutomationProperties.AccessibilityView="Raw" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" ContentTemplate="{TemplateBinding ContentTemplate}" ContentTransitions="{TemplateBinding ContentTransitions}" Content="{TemplateBinding Content}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Grid>
我想从 C# 中做到这一点,ControlTemplate 没有 Child 或 Children
And i want to do it from C# like, ControlTemplate not have Child or Children
Grid grid1 = new Grid();
ControlTemplate cTempl = new ControlTemplate();
cTempl.child.add(grid1);
推荐答案
我不确定您为什么需要更改后面的 ControlTemplate
代码,但不建议这样做.根据ControlTemplate 的说明
类:
I'm not sure why you need to change the ControlTemplate
code behind, but this is not recommended. According to the remarks of the ControlTemplate
class:
控件模板提供组成控件实例的视觉效果和部件,因为它出现在应用程序的 UI 中.在运行时,模板已被应用,因此所有从模板创建的部分现在都是控件的真正部分.
该模板已在运行时应用,在定义 ControlTemplate
时实际上只使用两个属性:TargetType
和隐式 XAML.如果您确实想将其设置为代码,您可以尝试使用 XamlReader
用于解析 XAML,例如:
The template has already be applied at run time and there are really only two properties you use when defining a ControlTemplate
: the TargetType
, and the implicit XAML. If you do want to set it code behind, you may try to use XamlReader
for parsing XAML, for example:
const string xaml = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Rectangle Stroke=\"Red\" StrokeThickness=\"3\" /></ControlTemplate>";
ControlTemplate сt=(ControlTemplate)XamlReader.Load(xaml);
同样,不推荐这样做.想想你为什么需要这个功能.您可以直接在 XAML 中更改它,或创建自定义控件以使用 OnApplyTemplate
方法设置您自己的 ControlTemplate
.
Again, this is not recommended. Think about why you need this feature. You could directly change it in XAML, or create a custom control to set your own ControlTemplate
with OnApplyTemplate
method.
这篇关于如何在 UWP C# 中将网格添加到 ControlTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!