向ObservableCollection中添加数据不会更新ListBox条目
本文关键字:更新 ListBox 条目 数据 ObservableCollection 添加 | 更新日期: 2023-09-27 18:02:02
我有一个UserControl绑定到一个ICollectionView,我已经实现了过滤底层的ObservableCollection。
public partial class DataStorage : UserControl
{
public ObservableCollection<CardData> dataStore;
private ICollectionView cards;
private string filter;
public string itemsInList { get; set; }
public DataStorage()
{
// Default constructor
InitializeComponent();
// Set the dataStore to be ICollectionView
dataStore = new ObservableCollection<CardData>();
// Data Add
this.AddSample();
// Set the collection source
this.cards = CollectionViewSource.GetDefaultView(dataStore);
// set the filter
this.cards.Filter = ContainsFilter;
}
// Other content here...
当我初始化UserControl时,我向ObservableCollection添加了一些示例数据。然后,我将ICollectionView设置为ObservableCollection的默认视图,并分配了该过滤器。
在这一点上,所有的工作按计划进行,当我更新TextBox控件,它将过滤样本数据。
输出Pic
如果我再次调用AddSample()方法向ObservableCollection添加更多的数据,这些更改不会反映在UI中。
public void AddSample()
{
dataStore.Add(new CardData("tesat1", false, 1, 0));
dataStore.Add(new CardData("test2", false, 2, 0));
dataStore.Add(new CardData("test3", false, 3, 2));
dataStore.Add(new CardData("test4", false, 4, 4));
dataStore.Add(new CardData("test5", false, 5, 0));
dataStore.Add(new CardData("help", false, 1, 0));
dataStore.Add(new CardData("fish", false, 2, 0));
dataStore.Add(new CardData("cat", false, 3, 2));
dataStore.Add(new CardData("tease", false, 4, 4));
dataStore.Add(new CardData("whelp", false, 5, 0));
上面是我的AddSample方法。每次添加更多数据后,我都尝试重新制作视图和过滤器。
// Set the collection source
this.cards = CollectionViewSource.GetDefaultView(dataStore);
// set the filter
this.cards.Filter = ContainsFilter;
XAML -if relevant
<TextBox x:Name="Filters" Text="{Binding Path=Filter, UpdateSourceTrigger=PropertyChanged}" Height="55" Width="335" VerticalContentAlignment="Center" FontSize="22" />
<ListBox Height="Auto" MaxHeight="200" MinHeight="0" x:Name="CardListBox"
ItemsSource="{Binding Path=Cards}"
SelectedItem="{Binding Path=SelectedCard}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=data}" Height="50" FontSize="22" VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我想我需要添加一个事件处理程序,当底层集合发生变化,但在这里面要做什么?因为当我调用AddSample()时,这肯定与更改集合的过程相同。
首先我假设Cards是ListBox的ItemsSource。接下来,当你将你的项目添加到Cards后,将ItemSource设置为null,然后将其设置回Cards或任何你的项目源