Pregunta

¿Cómo se determina la anchura del texto en un WPF TreeViewItem en tiempo de ejecución?

necesito para calcular una compensación para que pueda trazar una línea desde una hoja a la hoja de un TreeView diferente. Todas las propiedades 'width' devuelven un tamaño que es mucho más grande que el espacio ocupado por el texto real del nodo. Debe ser posible debido a que la función de selección no pone de manifiesto toda la fila. Estoy escribiendo el cliente en WPF y Silverlight.

¿Fue útil?

Solución 3

Tengo dos soluciones:

A) Utiliza el árbol visual

    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) Si no desea utilizar el árbol visual

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

Otros consejos

Usted no era muy específico en el texto o las etiquetas, así que estoy asumiendo que usted está tomando sobre TreeViewItem del .Net Framework.

Puede haber formas más sencillas, pero una posibilidad es utilizar el método Graphics.MeasureString. Se le da el tamaño en píxeles de un texto cuando se dibuja utilizando una fuente específica.

@mrphil: feto abortado dulce, eso da miedo

myTreeViewItem.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
Size s = myTreeViewItem.DesiredSize;
return s.Width;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top