Stojdza
Stojdza

Reputation: 445

TextBox.LineCount always -1 WPF

I created an textbox from code behind like this:

    TextBox txtPlainTxt = new TextBox();
    txtPlainTxt.Height = 200;
    txtPlainTxt.Width = 300;
    txtPlainTxt.TextWrapping = TextWrapping.Wrap;
    txtPlainTxt.Text = text;
    int lineCount = txtPlainTxt.LineCount;

I'm trying to get the LineCount property of a textbox but problem is that it always has the value of "-1". I guess it have something to do with that I created it from code behind and not in my xaml becouse when I create the exact same textbox in xaml, everything works fine and I get the correct number of lines in it. I tried to call UpdateLayout() method and also tried to call Focus() method like this:

txtPlainTxt.Focus();
txtPlainTxt.UpdateLayout();
txtPlainTxt.Focus();
txtPlainTxt.UpdateLayout();

But I still get the value of -1. How can I solve this problem?

Upvotes: 0

Views: 1478

Answers (1)

Arie
Arie

Reputation: 5373

That is happening because until your layout gets measured, you don't have ActualHeight and ActualWidth, so LineCount can't get calculated until that happens.

That means that you can only use LineCount property after your layout got measured & arranged.

(UpdateLayout() only notifies the layout engine that the layout should be updated and immediately returns.)

public partial class Window1 : Window
{
    TextBox txtPlainTxt = new TextBox();

    public Window1()
    {
        txtPlainTxt.Height = 200;
        txtPlainTxt.Width = 300;
        txtPlainTxt.TextWrapping = TextWrapping.Wrap;
        txtPlainTxt.Text = "some text some text some text some text some text";

        Grid.SetRow(txtPlainTxt, 0);
        Grid.SetColumn(txtPlainTxt, 0);
        gridMain.Children.Add(txtPlainTxt);

        // here it will be -1
        int lineCount = txtPlainTxt.LineCount;

        gridMain.LayoutUpdated += new EventHandler(gridMain_LayoutUpdated);
        txtPlainTxt.LayoutUpdated += new EventHandler(txtPlainTxt_LayoutUpdated);

    }

    void txtPlainTxt_LayoutUpdated(object sender, EventArgs e)
    {
        // the layout was updated, LineCount will have a value
        int lineCount = txtPlainTxt.LineCount;
    }

    void gridMain_LayoutUpdated(object sender, EventArgs e)
    {
        // here it will be correct too
        int lineCount = txtPlainTxt.LineCount;
    }
}

Upvotes: 2

Related Questions