-->

INotifyCollectionChanged不更新UI(INotifyCollectionCha

2019-09-29 13:36发布

我有一个类,如下图所示。 我为简洁,删除了所有功能

public class PersonCollection:IList<Person>
{}

现在我又多了一个模型类,如下图所示。 AddValueCommand是ICommand的类派生再次我omiting。

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到模型,如下图所示

 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" />

点击按钮时,我的列表框不与新值更新。 我很想念这里。

Answer 1:

INotifyCollectionChanged必须由集合类来实现。 不包含集合类。
您需要删除INotifyPropertyChangedDataContextClass并将其添加到PersonCollection



Answer 2:

代替使用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
介绍的ObservableCollection在WPF
在数据绑定一个MVVM的ObservableCollection



文章来源: INotifyCollectionChanged is not updating the UI