文本框不会在绑定列表更新时保持选择

Textbox doesn't keep selection on binded list update

在我的 ViewModel 中,我有一个 ObservableCollection 字符串,其中包含从以太网接收的所有消息:

public ObservableCollection<string> Messages { get; set; }

我用转换器将它绑定到视图中的文本框:

<TextBox Text="{Binding Messages, Converter={StaticResource ListToStringConverter}}" HorizontalAlignment="Center"/>

我的转换器很简单

string finalStr;
foreach(var v in Messages) 
{ 
    finalStr += v + "\n";
}
return finalStr;

当我 select 一些文本时,当新消息添加到我的消息时 selection 消失。

关于如何保持 selection 有什么想法吗?

您可以通过对 SelectionChanged 和 TextChanged 事件的一些处理来防止这种情况。

<TextBox Text="{Binding Messages, 
                        Converter={StaticResource ListToStringConverter}}"
         HorizontalAlignment="Center"
         SelectionChanged="TextBox_SelectionChanged"
         TextChanged="TextBox_TextChanged" />

然后,在处理程序中:

private int selectionStart;
private int selectionLength;

private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
    var textBox = sender as TextBox;
    selectionStart = textBox.SelectionStart;
    selectionLength = textBox.SelectionLength;
}

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    if (selectionLength > 0)
    {
        var textBox = sender as TextBox;
        textBox.SelectionStart = selectionStart;
        textBox.SelectionLength = selectionLength;
    }
}

这最好在具有附加属性的行为中进行,而不是在代码隐藏中进行,但您明白了。