INotifyCollectionChanged没有更新UI

本文关键字:UI 更新 INotifyCollectionChanged | 更新日期: 2023-09-27 18:11:34

我有一个如下所示的类。为了简洁,我删除了所有的函数

public class PersonCollection:IList<Person>
{}

现在我又多了一个Model类,如下所示。AddValueCommand是从iccommand派生的类,我又省略了。

public class DataContextClass:INotifyCollectionChanged
{
    private PersonCollection personCollection = PersonCollection.GetInstance();
    public IList<Person> ListOfPerson
    {
        get 
        {
            return personCollection;
        }            
    }
    public void AddPerson(Person person)
    {
        personCollection.Add(person);
        OnCollectionChanged(NotifyCollectionChangedAction.Reset);
    }

    public event NotifyCollectionChangedEventHandler CollectionChanged = delegate { };
    public void OnCollectionChanged(NotifyCollectionChangedAction action)
    {
        if (CollectionChanged != null)
        {
            CollectionChanged(this, new NotifyCollectionChangedEventArgs(action));
        }
    }       
    ICommand addValueCommand;
    public ICommand AddValueCommand
    {
        get
        {
            if (addValueCommand == null)
            {
                addValueCommand = new AddValueCommand(p => this.AddPerson(new Person { Name = "Ashish"}));
            }
            return addValueCommand;               
        }
    }
}

在主窗口中,我将UI绑定到Model,如下所示

 DataContextClass contextclass = new DataContextClass();           
 this.DataContext = new DataContextClass();

和我的UI看起来像下面所示

<ListBox Margin="5,39,308,113" ItemsSource="{Binding Path=ListOfPerson}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBox Height="20" Text="{Binding Path=Name}"></TextBox>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button Content="Button"  HorizontalAlignment="Left" Command="{Binding Path=AddValueCommand}" Margin="233,39,0,73" />

单击按钮时,我的列表框没有更新新值。

INotifyCollectionChanged没有更新UI

INotifyCollectionChanged必须由集合类实现。不能通过包含集合的类。
您需要将INotifyPropertyChangedDataContextClass中移除并添加到PersonCollection

不使用IList,使用ObservableCollection<T>并定义PersonCollection类,如下所示:

public class PersonCollection : ObservableCollection<Person>
{}

你可以在这里阅读更多关于ObservableCollection<T>类的信息,它是专门为WPF数据绑定场景中的集合更改通知而设计的。

从下面MSDN的定义可以看出,它已经实现了INotifyCollectionChanged

public class ObservableCollection<T> : Collection<T>, 
    INotifyCollectionChanged, INotifyPropertyChanged

更多帮助您在WPF中使用ObservableCollection类的文章如下:

创建并绑定到ObservableCollection
Wpf中ObservableCollection的介绍在MVVM中绑定ObservableCollection