Szymon Seliga
Szymon Seliga

Reputation: 820

Setting DataContext in UserControl from ViewModel

I have a View that contains a Listbox. I'll call it CityListingPage.xaml. This list page has a CityListingViewModel, that is binded with the View like somewhat like this:

DataContext="{Binding CityListing, Source={StaticResource Locator}}"

This works nicely. Now I what to change my page to a Pivot Control, where the Pivot Items, would be instances of CityListingViewModel, but obviously with different constructor data (ie. Country)

I extracted the ListBox into a UserControl. Now I'm struggling how to make this work so that for each list I get a new instance of the CityListingViewModel.

I tried creating in the ViewModelLocator a collection of CityListingViewModels but how do I pass the a CityListingViewModel instance to the UserControls DataContext?

Perhaps there is a different, better way of doing this?

Upvotes: 0

Views: 723

Answers (3)

AxelEckenberger
AxelEckenberger

Reputation: 16926

The following are two answers for using a collection to create panorama pages. But I am quite sure that the approach can be adapted to pivot pages:

The second post should be more relevant.

Upvotes: 1

Darkside
Darkside

Reputation: 1739

If you are thinking of partitioning the same data over multiple views on a pivot page then I would suggest NOT using several view models, especially if it is the same datasource you are using for all the data.

Simply have a parameter which each view would bind to and use Linq to control what data is visible to that parameter.

So you will have the variable which will contain all the data to be displayed and one parameter per view querying that data.

Upvotes: 0

Chris Koenig
Chris Koenig

Reputation: 2748

Without seeing your code, I'm going to do a little guessing, but I think you can do it directly via data binding. Since each pivot item is getting an instance of CityListingViewModel, you can just pass that binding along to the UserControl:

If you post a little more code showing what you're trying to do, we might be able to be of more help.

Upvotes: 1

Related Questions