Search code examples
c#wpftextboxcultureinfotext-formatting

setting textBox.MinWidth to largest required space for current culture, font, etc


I'd like my wpf textbox to have a minimum width large enough to accomodate exactly 1 character as it would be drawn depending on the font family, font size, and other properties of the wpf text(box) AND the current culture (could be any). Can I just set the MinWidth property to the FontSize property to achieve this? That's probably too simple to work..


Solution

  • You can use TextRenderer.MeasureText(string, font).

    Here is an example:

    TextBox textBox = new TextBox();
    Size size = TextRenderer.MeasureText("A", textBox.Font);
    textBox.Width = size.Width;