簡體   English   中英

如何在xaml Textblock或富文本框中附加文本?

[英]How to append Text in xaml Textblock or rich textbox?

我正在Windows 8 Windows Metro Style App中創建一個聊天應用程序。 我需要將對話附加到XAML中的richtextblocktextblock中。 有人會告訴我這個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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM