How to Add Grid to ControlTemplate in UWP C#

人盡茶涼 提交于 2019-12-13 03:06:21

问题


I want add grid to ControlTemplate using C# in UWP application

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>

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

回答1:


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:

Control templates provide the visuals and parts that make up an instance of a control as it appears in an app's UI. At run time, the template has already been applied, and so all the parts that were created out of the template are now truly parts of the control.

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

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.



来源:https://stackoverflow.com/questions/47457394/how-to-add-grid-to-controltemplate-in-uwp-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!