如何在运行时确定 WPF TreeViewItem 中文本的宽度? [英] How do you determine the width of the text in a WPF TreeViewItem at run time?

查看:35
本文介绍了如何在运行时确定 WPF TreeViewItem 中文本的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在运行时确定 WPF TreeViewItem 中文本的宽度?

How do you determine the width of the text in a WPF TreeViewItem at run time?

我需要计算一个偏移量,以便我可以从一个叶子到另一个 TreeView 的叶子绘制一条线.所有宽度"属性返回的大小都比节点的实际文本占用的空间大得多.这一定是可能的,因为 Select 功能不会突出显示整行.我正在用 WPF 和 Silverlight 编写客户端.

I need to calculate an offset so I can draw a line from one leaf to the leaf of a different TreeView. All the 'width' properties return a size that is way bigger than the space taken up by the actual text of the node. It must be possible because the Select feature doesn't highlight the entire row. I'm writing the client in WPF and Silverlight.

推荐答案

我有两个解决方案:

A) 使用可视化树

    TreeViewItem selected = (TreeViewItem)dataSourceTreeView.SelectedItem;
    double textWidth = 0;
    double expanderWidth = 0;
    Grid grid = (Grid)VisualTreeHelper.GetChild(selected, 0);

    ToggleButton toggleButton = (ToggleButton)VisualTreeHelper.GetChild(grid, 0);
    expanderWidth = toggleButton.ActualWidth;

    Border bd = (Border)VisualTreeHelper.GetChild(grid, 1);
    textWidth = bd.ActualWidth;

B) 如果你不想使用可视化树

B) If you don't want to use the visual tree

    TreeViewItem selected = (TreeViewItem)dataSourceTreeView.SelectedItem;
    double textWidth = 0;
    Typeface typeface = new Typeface(selected.FontFamily,
        selected.FontStyle, selected.FontWeight, selected.FontStretch);

    GlyphTypeface glyphTypeface;
    if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
            throw new InvalidOperationException("No glyphtypeface found");

    string headerText = (string)selected.Header;
    double size = selected.FontSize;

    ushort[] glyphIndexes = new ushort[headerText.Length];
    double[] advanceWidths = new double[headerText.Length];

    for (int n = 0; n < headerText.Length; n++)
    {
            ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[headerText[n]];
            glyphIndexes[n] = glyphIndex;

            double width = glyphTypeface.AdvanceWidths[glyphIndex] * size;
            advanceWidths[n] = width;

            textWidth += width;
    }

这篇关于如何在运行时确定 WPF TreeViewItem 中文本的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆