1

im using a WPF RichTextbox to display messages from other people and myself. The issue is not when receiving messages. since the allignment is perfect for left alligned text as traditionally done in messanging apps. The issue is when trying to allign what the user is sending. I've tried using a measure string function to get the width of the string, which i can then subtract from the conversationbox(RichTextBox) viewport width and then using string.padleft to add spaces before, however it seems that the MeasureString function makes the string out to be wider than what it actually is when the text is appended to the RichTextBox.

I have found a lot of solutions that work for winforms, but not yet any for WPF. Any help is valuable, and thanks in advance.

MeasureString function:

private int MeasureString(string candidate)
    {
        var formattedText = new FormattedText(
            candidate,
            CultureInfo.CurrentCulture,
            FlowDirection.LeftToRight,
            new Typeface(this.ConversationBox.FontFamily, this.ConversationBox.FontStyle, this.ConversationBox.FontWeight, this.ConversationBox.FontStretch),
            this.ConversationBox.FontSize,
            Brushes.Black,
            new NumberSubstitution(),
            1);

        return (int)formattedText.WidthIncludingTrailingWhitespace;
    }
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66

0 Answers0