WPF – 如何在代码隐藏中创建的控件模板中附加 VisualStateGroups?
WPF – how to attach VisualStateGroups in control template created in code-behind?
<ControlTemplate TargetType="{x:Type TreeViewItem}">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
…
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
…
</Grid>
</ControlTemplate>
先前XAML控件模板的替代方案是代码隐藏C#.[=16中的以下示例=]
var rootGrid = new FrameworkElementFactory(typeof(Grid));
var controlTemplate = new ControlTemplate(typeof(TreeViewItem))
{
VisualTree = rootGrid
};
如何在代码隐藏版本中附加VisualStateGroup
?我假设我需要瞄准 FrameworkElementFactory
。方法 FrameworkElementFactory.AppendChild()
需要另一个 FrameworkElementFactory
.
FrameworkElementFactory 是根据 Microsoft docs.
创建控件模板的已弃用方法
This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.
您可以在代码中将模板构建为字符串,然后使用 XamlReader
的 Load
方法。这将使 VisualStateGroups 的实现变得容易!
希望对您有所帮助。
<ControlTemplate TargetType="{x:Type TreeViewItem}">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
…
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
…
</Grid>
</ControlTemplate>
先前XAML控件模板的替代方案是代码隐藏C#.[=16中的以下示例=]
var rootGrid = new FrameworkElementFactory(typeof(Grid));
var controlTemplate = new ControlTemplate(typeof(TreeViewItem))
{
VisualTree = rootGrid
};
如何在代码隐藏版本中附加VisualStateGroup
?我假设我需要瞄准 FrameworkElementFactory
。方法 FrameworkElementFactory.AppendChild()
需要另一个 FrameworkElementFactory
.
FrameworkElementFactory 是根据 Microsoft docs.
创建控件模板的已弃用方法This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.
您可以在代码中将模板构建为字符串,然后使用 XamlReader
的 Load
方法。这将使 VisualStateGroups 的实现变得容易!
希望对您有所帮助。