WPF –如何将VisualStateGroups附加到在后台代码中创建的控件模板中?

问题描述 投票:0回答:1
<ControlTemplate TargetType="{x:Type TreeViewItem}">
    <Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
            …
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        …
    </Grid>
</ControlTemplate>

先前的XAML控件模板的替代品是代码隐藏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个回答
0
投票
FrameworkElementFactory是根据Microsoft docs创建控件模板的不建议使用的方法。

此类是以不推荐的方式以编程方式创建模板,这些模板是FrameworkTemplate的子类,例如ControlTemplate或DataTemplate;使用此类创建模板时,并非所有模板功能都可用。

建议以编程方式创建模板的方法是使用XamlReader类的Load方法从字符串或内存流中加载XAML。

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

我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.