How to get text pixel size in DataGridTextColumn

162 views Asked by At

I'm trying to find out the pixel size of the text (with the maximum length) in a DataGridTextColumn in WPF using the MVVM pattern so that I can set the minimum width of the DataGridTextColumn.

Can anyone help me with this?

1

There are 1 answers

0
Dilshod K On

You can get the text size from font using this method:

    SizeF GetSizeOfFont(Font font, string text)
    {
        SizeF size;
        using (var graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1)))
        {
            var sty = DataGrid;
            size = graphics.MeasureString(text, font);
        }
        return size;
    }

Example:

    var font = new Font("Segoe UI", 50, GraphicsUnit.Point);
    var size = GetSizeOfFont(font, "Hello World");
    var width = size.Width;
    var heidht = size.Height;