C#中的Richtextbox如何实现文本的左右对齐?

3
我想在C#中制作一个框,其中我可以将某些文本左对齐和某些文本右对齐显示。例如:

代码

If (msg from admin)
   richTextBox.Append(rightAligned(msg))
else
   richTextBox.Append(leftAligned(msg))

我尝试使用richTextBox的SelectionAlignment功能,但它会将特定格式应用于文本框中的所有文本。我该如何实现所需的结果?任何帮助都将不胜感激。

最好使用Panel而不是RichTextBox... - yash
4个回答

3
你可以在richTextBox中使用Environment.NewlineRichTextBox.SelectionAlignment
例如:
if (msg from admin) {
    richTextBox.AppendText(Environment.NewLine + msg);
    richTextBox.SelectionAlignment = HorizontalAlignment.Right;
} else {
    richTextBox.AppendText(Environment.NewLine + msg);
    richTextBox.SelectionAlignment = HorizontalAlignment.Left;
}

1
非常感谢,这对我的示例完美地起作用。 - Rukshod

2

要仅设置添加的文本的对齐方式,您需要仅选择添加的文本,然后使用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.
    }

1

This Could be done as well :)

 If (...)
    {
       textBox1.TextAlign = HorizontalAlignment.Left;
       textBox1.Text = " Blah Blah ";
    }
else
   {
       textBox1.TextAlign = HorizontalAlignment.Right;
       textBox1.Text = " Blah Blah Right";
   }

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接