我的ObservableCollection列表不更新 View 。我使用MVVM Light
这是我的虚拟机
public class MainViewModel : ViewModelBase{
public ObservableCollection<ProductModel> Products { get; set; }
private void GetData()
{
//getting data here
Products = new ObservableCollection<ProductModel>();
foreach (var item in myData)
{
Products.Add(item);
}
}}
XAML:
DataContext="{Binding Source={StaticResource Locator}, Path=Main}"><FlowDocumentReader BorderBrush = "Black" BorderThickness="2">
<FlowDocument>
<BlockUIContainer>
<ListView BorderThickness = "2" ItemsSource="{Binding Products}">
<ListView.View>
<GridView>
<GridViewColumn Header = "Lp." DisplayMemberBinding="{Binding Path=OrdinalNumber}" Width="100"/>
<GridViewColumn Header = "id" DisplayMemberBinding="{Binding Path=id}" Width="100"/>
<GridViewColumn Header = "Name" DisplayMemberBinding="{Binding Path=Name}" Width="100"/>
<GridViewColumn Header = "Quantity" DisplayMemberBinding="{Binding Path=Quantity}" Width="100"/>
<GridViewColumn Header = "NetPrice" DisplayMemberBinding="{Binding Path=NetPrice}" Width="100"/>
<GridViewColumn Header = "GrossPrice" DisplayMemberBinding="{Binding Path=GrossPrice}" Width="100"/>
<GridViewColumn Header = "TotalCost" DisplayMemberBinding="{Binding Path=TotalCost}" Width="100"/>
</GridView>
</ListView.View>
</ListView>
</BlockUIContainer>
</FlowDocument>
对我来说,看起来不错。我不知道问题出在哪里
最佳答案
这不是ObservableCollection的问题,而是设置Products属性的问题。
Products = new ObservableCollection<ProductModel>();
您在GetData方法中进行了设置,但从未将其通知给 View ,因此它未绑定(bind)到ObservableCollection。
您可以改为在构造函数中设置属性,也可以在该属性上使用INotifyPropertyChanged。
关于c# - ObservableCollection不会更新ListView,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41783790/