wpf 添加项目时,Observablecollection 不更新列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35975364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:42:29  来源:igfitidea点击:

Observablecollection not updating list, when an item gets added

c#wpflistviewmvvm

提问by HaloMediaz

I'm using the MVVM pattern and want to update a ListView using an observable collection. I went through several SO questions, but cannot see what I'm doing wrong. Any help is much appreciated. Thanks.

我正在使用 MVVM 模式并希望使用可观察集合更新 ListView。我经历了几个 SO 问题,但看不出我做错了什么。任何帮助深表感谢。谢谢。

View.xaml

查看.xaml

Namespace: xmlns:local="clr-namespace:MusicPlayer.ViewModel"

命名空间: xmlns:local="clr-namespace:MusicPlayer.ViewModel"

DataContext

数据上下文

<UserControl.DataContext>
    <local:AllTracksViewModel/>
</UserControl.DataContext>

ListView

列表显示

<ListView x:Name="TrackListView" 
                  ItemsSource="{Binding Path=TrackListObservable}">
...
<ListView.View>
   <GridView>
     <GridViewColumn Header="Title" Width="250" DisplayMemberBinding="{Binding Title}" />
      <GridViewColumn Header="Album" Width="200" DisplayMemberBinding="{Binding Album}" />
      <GridViewColumn Header="Artist" Width="150" DisplayMemberBinding="{Binding Artist}" />
      <GridViewColumn Header="Duration" Width="100" DisplayMemberBinding="{Binding FormattedDuration}" />
      </GridView>
    </ListView.View>
</ListView>

ViewModel.cs

视图模型.cs

public class AllTracksViewModel
{
    public ObservableCollection<Track> TrackListObservable { get; private set; }

    public AllTracksViewModel()
    {
        TrackListObservable = new ObservableCollection<Track>();
    }
}

I verified that items are definitely getting added to the observable. Again, thanks for the help.

我确认项目肯定会添加到可观察对象中。再一次感谢你的帮助。

回答by Arnaud Weil

Change your code to this:

将您的代码更改为:

public class AllTracksViewModel : INotifyPropertyChanged
{
    ObservableCollection<Track> trackListObservable;

    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<Track> TrackListObservable {
      get { return trackListObservable; }
      set {
        trackListObservable = value;
        if(PropertyChanged!=null) {
          PropertyChanged(this, new PropertyChangedEventArgs("TrackListObservable"));
        }
      }
}

    public AllTracksViewModel()
    {
        TrackListObservable = new ObservableCollection<Track>();
    }
}

Just to explain why: every property of your ViewModel should notify of its changes.

只是为了解释原因:您的 ViewModel 的每个属性都应该通知其更改。

回答by M.kazem Akhgary

You should write this as itemsource

你应该把它写成 itemsource

ItemsSource="{Binding ViewModel.TrackListObservable}"

And also set data context of windows to it self.

并将窗口的数据上下文设置为它自己。

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...

With this property in MainWindow.

在 MainWindow 中使用此属性。

public AllTracksViewModel ViewModel { get; } = new AllTracksViewModel();

Note that you have to add items to this property. ViewModel.TrackListObservable

请注意,您必须向此属性添加项目。 ViewModel.TrackListObservable

You should also remove

你也应该删除

<UserControl.DataContext>
    <local:AllTracksViewModel/>
</UserControl.DataContext>

since the data context is the main window it self, thats why itemsource is set to ViewModel.TrackListObservable

由于数据上下文是它自己的主窗口,这就是为什么将 itemsource 设置为 ViewModel.TrackListObservable

回答by StepUp

Your code looks correctly. However, I cannot see the method which populates your TrackListObservable. I suggest to you to call a populating method FillDatainside of a constructor. Let me show an example:

您的代码看起来正确。但是,我看不到填充您的TrackListObservable. 我建议您FillData在构造函数中调用填充方法。让我举个例子:

public class AllTracksViewModel
{
    private ObservableCollection<Track> _trackListObservable;
    public ObservableCollection<Track> TrackListObservable
    {
       get { return _trackListObservable; }
       set { 
             _trackListObservable = value;                 
           }
    }

    public AllTracksViewModel()
    {
         FillData();
    }

    private void FillData()
    {
       _trackListObservable = new ObservableCollection<Track>();
        for (int i = 0; i < 30; i++)
        {
           TrackListObservable.Add(new Track() { Title = "Ben & Joseph " + i.ToString(), 
                                                                 Artist = "Albahari" });
        }   
    }
}

Please, see a work example of binding ListView using MVVM pattern.

请参阅使用 MVVM 模式绑定 ListView的工作示例

回答by Vinod Kumar

Here your Property TrackListObservablemust be a INotify Property or Dependency Property.So that only you can achieve the result what you want.

在这里,您的属性TrackListObservable必须是 INotify 属性或依赖属性。这样只有您才能达到您想要的结果。

Refer the below link regards INotify Property: https://msdn.microsoft.com/library/ms743695(v=vs.100).aspx

请参阅以下有关 INotify 属性的链接:https://msdn.microsoft.com/library/ms743695(v =vs.100).aspx