Calculate TextBox size from text size without actual TextBox

289 views Asked by At

In a UWP app, is it possible to use the size and font of some text to calculate how big a TextBox would need to be to hold that text without scrolling?

This could be useful in designing an overall layout -- depending on the size of the TextBox, one might switch to a different configuration.

I'm going to be doing all this in code, not in xaml, as my app is cross-platform, and its graphical layout brains are in the platform-independent part.

If knowing the size is not possible, even knowing either of its dimensions would be nice, if that is possible.

1

There are 1 answers

0
Jet  Chopper On

Try this:

public sealed partial class MainPage
{
    private TextBox _textBox;
    private TextBlock _textBlock;

    public MainPage()
    {
        InitializeComponent();
        Loaded += MainPage_Loaded;
    }
    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        _textBlock = new TextBlock
        {
            Margin = new Thickness(10000, 10000, 0, 0),
        };
        MainGrid.Children.Add(_textBlock);

        _textBox = new TextBox
        {
            Width = _textBlock.ActualWidth + 64, //is for clear button space
            Height = _textBlock.ActualHeight,
        };
        _textBox.TextChanged += _textBox_TextChanged;
        MainGrid.Children.Add(_textBox);
    }

    private void _textBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        _textBlock.Text = _textBox.Text;
        _textBox.Width = _textBlock.ActualWidth + 64;
        _textBox.Height = _textBlock.ActualHeight;
    }
}

It is not the perfect solution but may fit.

You just create somewhere off the screen textBlock and follow its size.

XAML has only 1 Grid x:Name="MainGrid"