【发布时间】:2021-01-10 21:03:41
【问题描述】:
背景:在我看来,我有一个TextBlock 和一个TextBox。一旦 TextBox 中的文本发生更改,TextChanged 事件就会被触发,并且在过滤列表后,我想更新绑定到 TextBlock 的属性。
在我的例子中,它是一个显示当前列表中联系人数量的计数器。
问题:当我调试时,属性 (ContactsCount) 总是会正确更新,但仅在代码中而不是在 UI 中。奇怪的是,UI 仅在我从 TextBox 中删除文本后更新到最后一个列表计数,而不是实际的。
代码
查看:
<TextBlock Text="{Binding ContactsCount, UpdateSourceTrigger=PropertyChanged}"
d:Text="4 Contacts"/>
<xctk:WatermarkTextBox Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Watermark="Search Contact"
Margin="20,10">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<i:InvokeCommandAction Command="{Binding Path=SearchBoxTextChanged}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</xctk:WatermarkTextBox>
视图模型:
public string ContactsCount
{
get => contactsCount;
set
{
contactsCount = value;
OnPropertyChanged(ContactsCount);
}
}
public string SearchText
{
get => searchText;
set
{
searchText = value;
OnPropertyChanged(SearchText);
}
}
public CommandHandler SearchBoxTextChanged { get; set; }
SearchBoxTextChanged = new CommandHandler(TextChanged);
private void TextChanged()
{
var filteredList = contactsList.Where(c => c.FirstName != null && c.FirstName.Contains(searchText.ToLower(), StringComparison.OrdinalIgnoreCase) ||
c.SecondName != null && c.SecondName.Contains(searchText.ToLower(), StringComparison.OrdinalIgnoreCase));
Contacts = new ObservableCollection<Contact>(filteredList);
// Bug: Doesn't update the UI after ContactsCount gets changed
ContactsCount = $"{Contacts.Count} Contacts";
}
【问题讨论】:
标签: c# wpf xaml data-binding