【问题标题】:How do you determine the width of the text in a WPF TreeViewItem at run time?如何在运行时确定 WPF TreeViewItem 中文本的宽度?
【发布时间】:2010-10-29 02:56:18
【问题描述】:

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

我需要计算一个偏移量,这样我就可以从一个叶子到另一个 TreeView 的叶子画一条线。所有 'width' 属性返回的大小都比节点的实际文本占用的空间大得多。这一定是可能的,因为“选择”功能不会突出显示整行。我正在用 WPF 和 Silverlight 编写客户端。

【问题讨论】:

    标签: wpf silverlight treeview treeviewitem


    【解决方案1】:

    @mrphil:可爱的流产胎儿,太可怕了

    myTreeViewItem.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
    Size s = myTreeViewItem.DesiredSize;
    return s.Width;
    

    【讨论】:

    • 感谢您的尝试,但您的回答对我不起作用,因为: 1. 您有错字。 DesireSize 是一个属性而不是一个方法所以 86 ()。 2. 你会发现这实际上给了你整个树的宽度,而不是那个特定的项目。 3. 它报告的大小似乎涉及某种填充,并且仍然大于我的代码报告的答案。
    • 好的 - 在这种情况下,使用 Snoop (blois.us/Snoop) 找到合适的测量对象
    【解决方案2】:

    我有两个解决方案:

    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) 如果你不想使用可视化树

        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;
        }
    

    【讨论】:

      【解决方案3】:

      您对文本或标签不是很具体,所以我假设您正在了解 .Net Framework 的 TreeViewItem。

      可能有更简单的方法,但一种可能性是使用 Graphics.MeasureString 方法。当使用特定字体绘制时,它会为您提供以像素为单位的文本大小。

      【讨论】:

      • 是的,我的意思是 .Net。我应该更具体。我正在用 WPF 和 Silverlight 编写客户端。已修复。
      • System.Drawing 命名空间在 Silverlight 中不可用,据我所知,没有等效的方法
      猜你喜欢
      • 2018-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多