【问题标题】:WPF – how to attach VisualStateGroups in control template created in code-behind?WPF – 如何在代码隐藏中创建的控件模板中附加 VisualStateGroups?
【发布时间】:2019-10-12 00:28:07
【问题描述】:
<ControlTemplate TargetType="{x:Type TreeViewItem}">
    <Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
            …
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        …
    </Grid>
</ControlTemplate>

之前的 XAML 控件模板的替代方案是 code-behind C# 中的以下示例。

var rootGrid        = new FrameworkElementFactory(typeof(Grid));
var controlTemplate = new ControlTemplate(typeof(TreeViewItem))
{
    VisualTree = rootGrid
};

如何在代码隐藏版本中附加VisualStateGroup?我假设我需要定位FrameworkElementFactory。方法 FrameworkElementFactory.AppendChild() 需要另一个 FrameworkElementFactory

【问题讨论】:

    标签: c# wpf code-behind controltemplate


    【解决方案1】:

    FrameworkElementFactory 是一种根据Microsoft docs 创建控件模板的已弃用方式。

    这个类是一种以编程方式创建模板的弃用方式,模板是 FrameworkTemplate 的子类,例如 ControlTemplate 或 DataTemplate;当您使用此类创建模板时,并非所有模板功能都可用。 以编程方式创建模板的推荐方法是使用 XamlReader 类的 Load 方法从字符串或内存流加载 XAML。

    您可以在代码中将模板构建为字符串,然后使用XamlReaderLoad 方法。这将使 VisualStateGroups 的实现变得容易!

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-07-16
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 2017-02-02
      相关资源
      最近更新 更多