向ObservableCollection添加数据不会更新ListBox条目

时间:2016-08-11 12:32:57

标签: c# wpf xaml listbox

我有一个绑定到ICollectionView的UserControl,我已经实现了它来过滤底层的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 of output

如果我再次调用我的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 - 相关

       <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()时更改集合的过程相同。

我的建议或想法值得赞赏。

1 个答案:

答案 0 :(得分:0)

首先,我假设将卡片作为ListBox的ItemsSource。将物品添加到卡片后,将ItemSource设置为null,然后将其设置回卡片或任何物品来源后立即生效。