我正在處理包含多行文本框的 UserControl。使用我的控件時,將能夠設置將顯示的文本。然后 TextBox 應調整其高度以使文本適合,寬度不能更改。所以這里是處理文本的屬性:[Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]public string TextToDisplay{ get { return internalTextBox.Text; } set { internalTextBox.Text = value; AdaptTextBoxSize(); }}我的第一次嘗試相當簡單:private void AdaptTextBoxSize(){ int nbLignes = internalTextBox.Lines.Length; float lineHeight = internalTextBox.Font.GetHeight(); internalTextBox.Height = (int)((nbLignes) * lineHeight);}這不起作用,因為它沒有考慮兩行文本之間的間距。所以我在文本中的行越多,我被剪掉的就越多。所以我試過這個:private void AdaptTextBoxSize(){ Size textSize = internalTextBox.GetPreferredSize(new Size(internalTextBox.Width, 0)); internalTextBox.Height = textSize.Height;}當文本框中的所有行都短于寬度時,這確實有效。但是當一行較長并且應該剪裁到下一行時,GetPreferredSize()返回的寬度大于我通過的寬度,因此高度太小。所以我再次改變并嘗試了這個:private void AdaptTextBoxSize(){ Size textSize = TextRenderer.MeasureText( internalTextBox.Text, internalTextBox.Font, new Size(internalTextBox.Width, 0), TextFormatFlags.WordEllipsis ); internalTextBox.Height = textSize.Height;}這次返回的 Width 是正確的,沒有超過我通過的那個,但是高度和之前的試驗一樣。所以它也不起作用。我為 嘗試了不同的組合TextFormatFlags,但無法找到獲勝的組合...這是框架的錯誤嗎?這里真正的問題是,有沒有我可以嘗試的另一件事,或者另一件事來實現我想要的(即在設置TextToDisplay屬性時自動調整高度)?
1 回答

慕的地8271018
TA貢獻1796條經驗 獲得超4個贊
TextBox.GetPositionFromCharIndex返回字符的像素位置。此處的位置表示頂部/左側,因此我們需要再添加一行..
這似乎在這里工作:
textBox.Height = textBox.GetPositionFromCharIndex(textBox4.Text.Length - 1).Y + lineHeight;
我得到這樣的行高:
int lineHeight = -1; using (TextBox t = new TextBox() { Font = textBox.Font }) lineHeight = t.Height;
我設置了Height
而不是ClientSize.Height
,這有點錯誤,除非BorderStyle
是None
。您可以更改為textBox.ClientSize = new Size(textBox.ClientSize.Width, l + lh);
- 1 回答
- 0 關注
- 508 瀏覽
添加回答
舉報
0/150
提交
取消