![](/img/trans.png)
[英]Rich formatting of text in a TextBlock using only DataBinding in XAML
[英]How to append Text in xaml Textblock or rich textbox?
我正在Windows 8 Windows Metro Style App中創建一個聊天應用程序。 我需要將對話附加到XAML中的richtextblock
或textblock
中。 有人會告訴我這個Code塊的等價物嗎?
public void AppendConversation(string str)
{
conversation.Append(str);
rtbConversation.Text = conversation.ToString();
rtbConversation.Focus();
rtbConversation.SelectionStart = rtbConversation.Text.Length - 1;
rtbConversation.ScrollToCaret();
rtbSendMessage.Focus();
}
由於WPF使用System.Windows.Controls
而不是System.Windows.Forms
,因此我們必須考慮以下內容
1. System.Windows.Controls.RichTextBox
沒有Text
的屬性來設置它的值,我們可以設置它的值來創建一個新的TextRange
類,因為控件依賴於TextPointer
,它可以使用TextRange
定義
string _Text = ""
new TextRange(
rtbConversation.Document.ContentStart,
rtbConversation.Document.ContentEnd).Text = _Text;
2. System.Windows.Controls.RichTextBox
中的選擇不依賴於int
但它們由TextPointer
。 所以,我們不能說
rtbConversation.SelectionStart = rtbConversation.Text.Length - 1;
但我們可以說
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.SelectionStart = rtbConversation.Text.Length - 1;
備注 :您始終可以使用RichTextBox.Selection.Start
在WPF中檢索選擇的開頭
注意 : RichTextBox.Selection.Start
輸出一個名為TextPointer
的類,但不輸出name int
的結構
3.最后, System.Windows.Controls.RichTextBox
沒有ScrollToCaret();
的定義ScrollToCaret();
。 在這種情況下,我們可能會使用以下關於控件rtbConversation
rtbConversation.ScrollToEnd();
rtbConversation.ScrollToHome();
rtbConversation.ScrollToHorizontalOffset(double offset);
rtbConversation.ScrollToVerticalOffset(double offset);
所以,你的void應該在WPF中看起來像這樣
例
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();
}
謝謝,
我希望這個對你有用 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.