UWP:在 TreeNode 中将文本设置为粗体

UWP: Set text to bold in TreeNode

我正在关注 Microsoft's documentationC++Universal Windows Platform 应用程序中实施 TreeView。我已经成功地能够使用以下代码创建一个节点的树视图:

XAML:

<TreeView x:Name="treeSolution"></TreeView>

C++:

TreeViewNode ^treeNode = ref new TreeViewNode();
treeNode->Content = "Hello";
treeSolution->RootNodes->Append(treeNode);

现在,我想将文本设置为粗体。我尝试了以下方法:

TextBlock ^textBlock = ref new TextBlock();
textBlock->Text = "Hello";
textBlock->FontWeight = Windows::UI::Text::FontWeights::Bold;
treeNode->Content = textBlock;
treeSolution->RootNodes->Append(treeNode);

代码以粗体显示 Windows.UI.Xaml.Controls.TextBlock 而不是 Hello

文档说 In Windows 10, version 1803, you have to retemplate the TreeView control and specify a custom ItemTemplate if your content is not a string. 然后给出了一个使用音乐和图片库的复杂示例。

有人可以提供一个简单的例子来说明如何将文本显示为粗体吗?谢谢。

您必须为 XAML 中的整个控件提供自定义样式才能设置 TreeViewItemDataTemplate:

<DataTemplate x:Key="TreeViewItemDataTemplate">
    <Grid Height="44">
        <TextBlock
            Text="{Binding Content}"
            HorizontalAlignment="Left"
            VerticalAlignment="Center"
            Style="{ThemeResource BodyTextBlockStyle}"
            FontWeight="Bold" />
    </Grid>
</DataTemplate>

<Style TargetType="TreeView">
    <Setter Property="IsTabStop" Value="False" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="TreeView">
                <TreeViewList x:Name="ListControl"
                              ItemTemplate="{StaticResource TreeViewItemDataTemplate}"
                              ItemContainerStyle="{StaticResource TreeViewItemStyle}"
                              CanDragItems="True"
                              AllowDrop="True"
                              CanReorderItems="True">
                    <TreeViewList.ItemContainerTransitions>
                        <TransitionCollection>
                            <ContentThemeTransition />
                            <ReorderThemeTransition />
                            <EntranceThemeTransition IsStaggeringEnabled="False" />
                        </TransitionCollection>
                    </TreeViewList.ItemContainerTransitions>
                </TreeViewList>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>