如何从TextBox只获取新文本?

时间:2011-03-25 21:06:23

标签: c# wpf xaml textbox

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...
*/  

如何从TextBox中仅获取新文本?

4 个答案:

答案 0 :(得分:4)

也许您应该使用TextChangedEventArgs.Changes属性:

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
}

答案 1 :(得分:3)

这样的东西?

private string old_text = "";

private void tbLog_TextChanged(object sender, TextChangedEventArgs e)
{
    if(old_text != tbLog.Text)
    {
        writeLog(tbLog.Text);
        old_text = tbLog.Text;
    }
}

答案 2 :(得分:3)

对于桌面WPF文本框,您应该能够使用TextChangedEventArgs.Changes枚举更改。请注意,单个事件可能包含多个更改。

TextChange类具有Offset,AddedLength和RemovedLength属性,可以为您提供更改的确切字符范围。

答案 3 :(得分:0)

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                
}