ObservableCollection不会更新ListView

时间:2017-01-21 19:52:01

标签: c# wpf xaml mvvm mvvm-light

我的ObservableCollection列表没有更新视图。我使用MVVM Light

这是我的VM

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>

对我来说看起来不错。我不知道问题出在哪里

2 个答案:

答案 0 :(得分:2)

这不是ObservableCollection的问题,而是设置Products属性。

Products = new ObservableCollection<ProductModel>();

您在GetData方法中设置它,但是您从不通知视图,因此它没有绑定到您的ObservableCollection。 您可以在构造函数中设置属性,也可以在属性上使用INotifyPropertyChanged。

答案 1 :(得分:0)

我发现你已经从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
}}