alansiqueira27
alansiqueira27

Reputation: 8506

How can I bind multiple datagrids source using MVVM?

Let me show u a simple problem with a solution, and then a more complex problem without a solution.

1) Imagine that I have a Shelf, which has a list of Products. I want to display a datagrid with the Products.

Solution: At View, I may insert a similar code at datagrid like this: "ItemSource = {Binding Products}". And then at ViewModel, I create an ObservableCollection property named "Products". Okay.

2) I have MANY shelves, and which one has many products. I want to display MANY datagrids one below each other. Each datagrid shows a list of products of one Shelf.

Now, how can I bind to MANY datagrids? It can be 3 datagrids. It can be 500 datagrids. How can I do this using MVVM?

Thanks. I hope u understood my question.

Upvotes: 0

Views: 334

Answers (2)

Nikita B
Nikita B

Reputation: 3333

I think the common approach is to create two view models

class Storage : ViewModelBase
{
     ObservableCollection<Shelf> Shelves { get; private set; }

     ...........
}


class Shelf : ViewModelBase
{
     ObservableCollection<Product> Products { get; private set; }

     ..........
}

Then you can simply create an ItemsControl with ItemsSource = "{Binding Shelves}" and specify ItemsTemplate property so each shelf in the collection is displayed as datagrid.

Upvotes: 0

user1599328
user1599328

Reputation: 191

Assuming that you have a collection of Shelf called Shelves on your ViewModel, you can use an ItemsControl, or a ListBox if you need selection, and define a DataTemplate:

<ItemsControl ItemsSource="{Binding Path=Shelves}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <DataGrid ItemsSource="{Binding Path=Products}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Upvotes: 4

Related Questions