I’m trying to calculate the height of an WPF textbox.
The code below does work for TextBlock, but returns a empty size for TextBox.
public partial class MainWindow : Window
{
public MainWindow()
{
var block = new TextBlock();
block.Measure(new Size(100, 100));
Console.WriteLine(block.DesiredSize); // {0,15.96} ok
var box = new TextBox();
box.Measure(new Size(100, 100));
Console.WriteLine(box.DesiredSize); // {0,0} why height = 0 ?
Is there a way to find the height of a TextBox without actually displaying it?
4
It should be sufficient to put the TextBox into some Panel:
var grid = new Grid();
var box = new TextBox();
grid.Children.Add(box);
grid.Measure(new Size(100, 100));
Debug.WriteLine(box.DesiredSize);
Output is:
6;17.96
Answering my own question : it looks like the TextBox must belong to the VisualTree to get a valid size.
public partial class MainWindow : Window
{
public MainWindow()
{
var box = new TextBox();
this.Content = box; // setting a parent
box.Measure(new Size(100, 100));
Console.WriteLine(box.DesiredSize); // {6,17.96} ok
Do you know if there is a completely off-screen solution?
Thanks.
0