INotifyCollectionChanged未更新UI

Vik*_*ram 1 c# wpf inotifycollectionchanged

我有一个课程,如下所示.为简洁起见,我删除了所有功能

public class PersonCollection:IList<Person>
{}
Run Code Online (Sandbox Code Playgroud)

现在我还有一个Model类,如下所示.AddValueCommand是从ICommand派生的类,我再次忽略了它.

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;               
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

 DataContextClass contextclass = new DataContextClass();           
 this.DataContext = new DataContextClass();
Run Code Online (Sandbox Code Playgroud)

我的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" />
Run Code Online (Sandbox Code Playgroud)

单击按钮时,我的列表框不会使用新值进行更新.我在这里失踪了什么.

VS1*_*VS1 10

而不是使用IListuse ObservableCollection<T>并定义您的PersonCollection类如下:

public class PersonCollection : ObservableCollection<Person>
{}
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关ObservableCollection<T>类的更多信息,该类专门针对WPF DataBinding方案中的集合更改通知而设计.

正如您在下面的MSDN中的定义中所看到的,它已经实现了INotifyCollectionChanged

public class ObservableCollection<T> : Collection<T>, 
    INotifyCollectionChanged, INotifyPropertyChanged
Run Code Online (Sandbox Code Playgroud)

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

创建和绑定到ObservableCollection
Wpf中
的ObservableCollection简介在MVVM中数据绑定ObservableCollection


Dan*_*rth 9

INotifyCollectionChanged必须由集合类实现.不是包含 该集合的类.
您需要删除INotifyPropertyChangedDataContextClass,并把它添加到PersonCollection.