简体   繁体   中英

Devexpress GridControl - refresh data in MVVM

My grid:

<dxg:GridControl x:Name="StatisticsGridLevel1"
                 dx:ThemeManager.ThemeName="Office2013"
                 DataContext="{Binding FooViewModel}"
                 ItemsSource="{Binding FooCollection}">

ViewModel:

private List<FooDto> fooCollection = new List<FooDto>();
public List<FooDto> FooCollection
{
    get
    {
        return this.fooCollection;
    }

    private set
    {
        this.fooCollection = value;
        this.NotifyPropertyChanged();
    }
}

And example method:

private void Foo()
{
    foreach (var element in collection)
    {
        this.fooCollection.Add(new FooDto()
        {
            X = element.Foo1,
            Y = element.Foo2,
            Z = element.Foo3
        });
    }
    this.NotifyPropertyChanged("FooCollection");
}

When I use ObservableCollection, everything works fine. But I want to use the List (that's not to notify in the loop).

The view refreshes after the start scroll on the grid. What is the problem?

I think a CollectionViewSource would work in your case. There are a lot of ways to go about creating one, in XAML, in your ViewModel, in your View's code-behind. I will throw together the easiest one for demonstration purposes which is creating a CollectionViewSource property on your ViewModel. I think some people might not necessarily like this approach - it kind of has the feel of mixing concerns. I am not sure I agree, though. If you take the position that a CollectionViewSource is an object model for a collection's view then I don't see anything wrong with having it in your ViewModel. But I think because it inherits from DependencyObject it gets stigmatized as being more of a view concern. Anyway, something like this would do what you want:

// Assuming this is your constructor
public ViewModel()
{
    this.FooViewSource.Source = this.fooCollection;
}

private readonly List<FooDto> fooCollection = new List<FooDto>();

private readonly CollectionViewSource fooViewSource;
public CollectionViewSource FooViewSource
{
    get { return this.fooViewSource; }
}

private void Foo()
{
    foreach (var element in collection)
    {
        this.fooCollection.Add(new FooDto()
        {
            X = element.Foo1,
            Y = element.Foo2,
            Z = element.Foo3
        });
    }
    this.FooViewSource.View.Refresh();
}

Then you would bind your ItemsSource property to the FooViewSource property of your ViewModel. A CollectionViewSource is pretty handy for other things as well. It supports sorting, filtering, selected items, maybe some other things I am forgetting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM