【问题标题】:Textbox doesn't keep selection on binded list update文本框不会在绑定列表更新时保持选择
【发布时间】:2015-09-02 08:38:15
【问题描述】:

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

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

我用转换器将它绑定到视图中的 texbox:

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

我的转换器很简单

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

当我选择一些文本时,当有新消息添加到我的消息时,选择会消失。

任何想法如何保持选择?

【问题讨论】:

  • 您可以尝试使用绑定到SelectedText(请参阅this 答案)。

标签: c# wpf textbox selection


【解决方案1】:

您可以通过对 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;
    }
}

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

【讨论】:

    猜你喜欢
    • 2013-10-23
    • 2014-04-12
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多