List<string> 在发生变化时不更新 UI

Har*_*ner 1 c# wpf xaml binding

<ListBox x:Name="MainList" HorizontalAlignment="Left" Height="468" Margin="10,10,0,0" VerticalAlignment="Top" Width="100" ItemsSource="{Binding Items,Mode=TwoWay}" DisplayMemberPath="Name"/>



[Serializable()]
public class MYcontainer : INotifyPropertyChanged,ISerializable
{
    private List<MYClass> _items = new List<MYClass>();
    public List<MYClass> Items
    {
        get{ return _items;}
       set { this._items =value;
        OnPropertyChanged("Items");
    }
public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName = null)
    {
        var eventHandler = this.PropertyChanged;
        if (eventHandler != null)
            eventHandler(this, new PropertyChangedEventArgs(propertyName));
    }  
}
Run Code Online (Sandbox Code Playgroud)

当我将一个项目添加到“项目”时,UI 不会更新,绑定工作正常,因为如果我关闭窗口并再次打开它,新项目会正确显示。

我究竟做错了什么?我知道如果我使用ObservableCollection它会正常工作,但不应该使用它List<>吗?我已经在另一个窗口中有一个 string[] 属性并且它更新得很好。

sa_*_*213 5

如果您不想使用 ues ObservableCollection,则必须实现INotifyCollectionChanged.

public partial class MainWindow : Window, INotifyCollectionChanged
{

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    public MainWindow()
    {
        InitializeComponent();
    }


    public void NotifyCollectionChanged(NotifyCollectionChangedAction action)
    {
        if (CollectionChanged != null)
        {
            CollectionChanged(this, new NotifyCollectionChangedEventArgs(action));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,ObservableCollection这一切都为你做了,将所有相同的逻辑添加到你List<T>只会创建一个自定义ObservableCollection,当 MS 已经为你做了这个时,我认为这没有意义