How to get only NEW text from TextBox?

2019-07-09 13:40发布

private void tbLog_TextChanged(object sender, TextChangedEventArgs e)
{
    //Get only NEW text added to Log
}

/*
    LOG
    old message...
    old message...
    old message...
    old message...
    NEW message...
    NEW message...
    NEW message...
    NEW message...
    NEW message...
*/  

How to I get only NEW text from the TextBox?

4条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-09 14:06

For desktop WPF text boxes, you should be able to use TextChangedEventArgs.Changes to enumerate the changes. Note a single event may contain several changes.

The TextChange class has Offset, AddedLength, and RemovedLength properties that give you the exact range of characters that were changed.

查看更多
Deceive 欺骗
3楼-- · 2019-07-09 14:16

Something like this?

private string old_text = "";

private void tbLog_TextChanged(object sender, TextChangedEventArgs e)
{
    if(old_text != tbLog.Text)
    {
        writeLog(tbLog.Text);
        old_text = tbLog.Text;
    }
}
查看更多
霸刀☆藐视天下
4楼-- · 2019-07-09 14:16

Perhaps you should be using the TextChangedEventArgs.Changes property:

var fullText = tbLog.Text;
if (e.Changes.Any())
{
    var additions = e.Changes.Where(tc => tc.AddedLength > 0);
    var newTexts = additions.Select(tc => fullText.Substring(tc.Offset, tc.AddedLength));

    // TODO: Do stuff with the new pieces of text
}
查看更多
Fickle 薄情
5楼-- · 2019-07-09 14:23
private void textTx1Asc_TextChanged(object sender, EventArgs e)
{                          
    string s;

    //get only the new chars
    s = textTx1Asc.Text;
    s = s.Remove(0, prev_len);          

    //update prev_len for next time
    prev_len = textTx1Asc.TextLength;

    //s contains only the new characters, process here                
}
查看更多
登录 后发表回答