WPF 使单个字符变为粗体(TreeViewItem)

WPF make single char bold (TreeViewItem)

我的 C# WPF-Application 有问题。 例如,我需要将 treeViewItem header 的第一个字母设为粗体。不幸的是,我找不到解决方案,有人知道我究竟该怎么做吗?

var treeViewItem = new TreeViewItem
                {
                    IsSelected = false,
                    Padding = new Thickness(105, 0, 105, 0),
                    Margin = new Thickness(0, 3, 0, 0),
                    HorizontalContentAlignment = HorizontalAlignment.Center
                };
                treeViewItem.Header = item.Header.ToString().Split(' ')[0] + _morseCodeAlphabet[i];

你可以这样做:

<TreeViewItem>
    <TreeViewItem.Header>
        <TextBlock Loaded="FrameworkElement_OnLoaded" Text="This is a test"/>
    </TreeViewItem.Header>
</TreeViewItem>
private void FrameworkElement_OnLoaded(object sender, RoutedEventArgs e)
{
    if (sender is TextBlock tb)
    {
        string text = tb.Text;
        tb.Text = "";
        int startIndex = 0;
        int endIndex = 1;
        tb.Inlines.Add(new Run(text.Substring(0, startIndex)));
        tb.Inlines.Add(new Bold(new Run(text.Substring(startIndex, endIndex - startIndex))));
        tb.Inlines.Add(new Run(text.Substring(endIndex)));
    }
}

结果: