我使用WPF RichTextbox显示来自其他人和我本人的消息。接收消息时不存在此问题。因为这种排列方式非常适合左对齐文字,就像传统上在messanging应用中所做的那样。问题是当尝试分配用户正在发送的内容时。我试过使用度量字符串函数来获取字符串的宽度,然后我可以从sessionboxbox(RichTextBox)视口宽度中减去该宽度,然后使用string.padleft在之前添加空格,但是似乎MeasureString函数使字符串要比将文本附加到RichTextBox时的实际宽度要宽。
我已经找到了许多适用于winforms的解决方案,但尚未适用于WPF。 任何帮助都是宝贵的,在此先感谢。
MeasureString函数:
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;
}