I'm creating a chat app in Windows 8 Windows Metro Style App. I need to append the conversation in a richtextblock
or textblock
in XAML. Would somebody tell me the equivalent for this Code block?
public void AppendConversation(string str)
{
conversation.Append(str);
rtbConversation.Text = conversation.ToString();
rtbConversation.Focus();
rtbConversation.SelectionStart = rtbConversation.Text.Length - 1;
rtbConversation.ScrollToCaret();
rtbSendMessage.Focus();
}
Since WPF uses System.Windows.Controls
instead of System.Windows.Forms
, we must consider the following
1. System.Windows.Controls.RichTextBox
does not have a property for Text
to set its value, we may set its value creating a new class of TextRange
since the control depends on TextPointer
which can be defined using TextRange
string _Text = ""
new TextRange(
rtbConversation.Document.ContentStart,
rtbConversation.Document.ContentEnd).Text = _Text;
2. Selections in System.Windows.Controls.RichTextBox
does not depend on int
yet they are held by TextPointer
. So, we can't say
rtbConversation.SelectionStart = rtbConversation.Text.Length - 1;
but we can say
int TextLength = new TextRange(
rtbConversation.Document.ContentStart,
rtbConversation.Document.ContentEnd).Text.Length;
TextPointer tr = rtbConversation.Document.ContentStart.GetPositionAtOffset(
TextLength - 1, LogicalDirection.Forward);
rtbConversation.Selection.Select(tr, tr);
which will do the same as rtbConversation.SelectionStart = rtbConversation.Text.Length - 1;
Remark: You can always retrieve the beginning of the selection in WPF using RichTextBox.Selection.Start
Notice: RichTextBox.Selection.Start
outputs a class of name TextPointer
but not a struct of name int
3. Finally, System.Windows.Controls.RichTextBox
does not have a definition for ScrollToCaret();
. In this case, we may use one of the following voids regarding your control rtbConversation
rtbConversation.ScrollToEnd();
rtbConversation.ScrollToHome();
rtbConversation.ScrollToHorizontalOffset(double offset);
rtbConversation.ScrollToVerticalOffset(double offset);
So, your void should look like this in WPF
Example
public void AppendConversation(string str)
{
conversation.Append(str) // Sorry, I was unable to detect the type of 'conversation'
new TextRange(rtbConversation.Document.ContentStart,
rtbConversation.Document.ContentEnd).Text =
conversation.ToString();
rtbConversation.Focus();
int TextLength = new TextRange(rtbConversation.Document.ContentStart,
rtbConversation.Document.ContentEnd).Text.Length;
TextPointer tr = rtbConversation.Document.ContentStart.GetPositionAtOffset(
TextLength - 1, LogicalDirection.Forward);
rtbConversation.Selection.Select(tr, tr);
rtbConversation.ScrollToEnd();
rtbSendMessage.Focus();
}
Thanks,
I hope you find this helpful :)