爲剛剛成立的附加文本的對齊方式,則需要選擇只是附加的文字,然後使用SelectionAlignment
屬性:
public static void AppendLineAndAlignText(this RichTextBox richTextBox, string text, HorizontalAlignment alignment)
{
if (string.IsNullOrEmpty(text))
return;
var index = richTextBox.Lines.Length; // Get the initial number of lines.
richTextBox.AppendText("\n" + text); // Append a newline, and the text (which might also contain newlines).
var start = richTextBox.GetFirstCharIndexFromLine(index); // Get the 1st char index of the appended text
var length = richTextBox.Text.Length;
richTextBox.Select(start, length - index); // Select from there to the end
richTextBox.SelectionAlignment = alignment; // Set the alignment of the selection.
richTextBox.DeselectAll();
}
經過測試後,似乎只要設置SelectionAlignment
就會工作,只要text
字符串不包含換行符,但是如果有嵌入的換行符,則只有最後一個添加的行會正確對齊。
public static void AppendLineAndAlignText(this RichTextBox richTextBox, string text, HorizontalAlignment alignment)
{
// This only works if "text" contains no newline characters.
if (string.IsNullOrEmpty(text))
return;
richTextBox.AppendText("\n" + text); // Append a newline, and the text (which must not also contain newlines).
richTextBox.SelectionAlignment = alignment; // Set the alignment of the selection.
}
來源
2014-11-21 06:44:26
dbc
這將是更好的,如果你使用面板而不是RichTExtBox ... – yash 2014-11-21 05:28:09