Search code examples
c++textuwptreeviewbold

UWP: Set text to bold in TreeNode


I am following Microsoft's documentation to implement a TreeView in a Universal Windows Platform app in C++. I have successfully been able to create a tree view with one node using the following codes:

XAML:

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

C++:

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

Now, I want to set the text to bold. I tried the following:

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

The code displays Windows.UI.Xaml.Controls.TextBlock instead of Hello in bold.

The documentation says that In Windows 10, version 1803, you have to retemplate the TreeView control and specify a custom ItemTemplate if your content is not a string. It then gives a complex example using the Music and Picture library.

Could somebody provide a simple example of how to display the text in bold? Thanks.


Solution

  • You have to provide a custom style for the whole control in XAML to be able to set the 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>