![](/img/trans.png)
[英]ListView bound to ObservableCollection<T> Doesn't update when Added to property
[英]ObservableCollection doesn't update ListView
我的ObservableCollection列表不会更新视图。 我使用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方法中进行了设置,但从未将其通知给视图,因此它未绑定到ObservableCollection。 您可以改为在构造函数中设置属性,也可以对该属性使用INotifyPropertyChanged。
我看到您已经从ViewModelBase继承了,因此您不需要这样做:
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
相反,您可以执行以下操作:
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);
}
RaisePropertyChanged(nameof(Products)); // you are missing this
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.