【问题标题】:How to Add Grid to ControlTemplate in UWP C#如何在 UWP C# 中将网格添加到 ControlTemplate
【发布时间】:2017-11-24 16:53:23
【问题描述】:

我想在 UWP 应用程序中使用 C# 将网格添加到 ControlTemplate

例如,我有 XAML 代码,例如:

<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 没有孩子或孩子

Grid grid1 = new Grid();
ControlTemplate cTempl = new ControlTemplate();
cTempl.child.add(grid1);

【问题讨论】:

  • 模板是一个模板,您不会在运行时创建控件的实例并将其添加到模板中。如果要以编程方式创建模板,则应使用 Sunteen Wu 建议的 XamlReader.Load 方法。但是在 XAML 中定义一个模板,然后尝试在运行时以编程方式对其进行修改是没有意义的。

标签: c# uwp uwp-xaml


【解决方案1】:

我不确定您为什么需要更改后面的ControlTemplate 代码,但不建议这样做。根据ControlTemplate类的备注:

控件模板提供构成控件实例的视觉效果和部件,因为它出现在应用的 UI 中。在运行时,模板已被应用,因此所有从模板创建的部分现在都真正成为控件的一部分。

该模板已在运行时应用,在定义ControlTemplate 时实际上只有两个属性:TargetType 和隐式 XAML。如果您确实想设置它的代码,您可以尝试使用XamlReader 来解析 XAML,例如:

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

【讨论】:

  • 孙婷,谢谢。根据我的要求,我不应该触摸 XAML。我通过使用模板来做到这一点(你提供的不是推荐的例子)。但我正在寻找代码隐藏的解决方案。
  • @Mahesh 正如我上面提到的,在定义ControlTemplate 时实际上只有两个属性,您不能在代码后面设置它。考虑您的要求并尝试其他方式。并检查我提到的最后一段。
  • 你的意思是 .Parse(xaml) 吗?
猜你喜欢
  • 2020-01-30
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 2019-02-14
  • 2022-01-22
  • 1970-01-01
  • 2017-11-22
相关资源
最近更新 更多