2015-04-23 74 views
0

我創建的代碼的文本框的背後是這樣的:TextBox.LineCount總是-1 WPF

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

我試圖讓一個文本框,但問題的LineCount特性是它總是有「價值-1" 。我想這與我從後面的代碼創建它有關,而不是在我的xaml中,當我在xaml中創建完全相同的文本框時,一切正常,我得到正確的行數。 我試着打電話給UpdateLayout請()方法,也試圖打電話焦點()方法是這樣的:

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

但我仍然得到值爲-1。我怎麼解決這個問題?

+0

是否有任何理由,你爲什麼會想在代碼中的XAML來創建這個後面,而不是? – Staeff

回答

2

發生這種情況的原因是,直到您的佈局得到測量,您沒有ActualHeightActualWidth,所以LineCount無法計算,直到發生這種情況。

這意味着你只能使用LineCount屬性之後你的佈局測量&安排。

UpdateLayout()只通知佈局應該更新的排版引擎,並立即返回。)

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; 
    } 
}