你如何在运行时确定在WPF TreeViewItem项文本的宽度是多少?
-
06-09-2019 - |
题
你如何在运行时确定在WPF TreeViewItem项文本的宽度是多少?
我需要计算的偏移量,以便可以通过一个叶画一条线到一个不同的树视图的叶。所有的“宽”属性返回一个大小比由节点的实际文本所占用的空间更强壮。它必须是可能的,因为选择功能并不突出整个行。我正在写在WPF和Silverlight客户端。
解决方案 3
我有两个解决方案:
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;
}
其他提示
您是不是在文字或标记非常具体的,所以我假设你正在做有关.NET Framework的树型视图。
有可能是更容易的方法,但一种可能性是使用Graphics.MeasureString方法。使用特定字体绘制时,它提供在文本的像素的尺寸。
@mrphil:甜流产胎儿,这是可怕的
myTreeViewItem.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
Size s = myTreeViewItem.DesiredSize;
return s.Width;
不隶属于 StackOverflow