Mekon
Mekon

Reputation: 101

How to pass bound data item to a ListBox item's ViewModel?

Trying to solve a very simple problem using mvvm-light, but after days of sifting through StackOverflow and lots of Google searches, I have not come up with a simple solution.

I have a ListBox with a dataTemplate. The dataTemplate contains one userControl to display the content

<ListBox ItemSource={Binding Posts} >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ctl:PostControl/>  <-- child control I'm trying to pass data to
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I've got viewModels on both the parent page (used to bind to the posts, no problem there) and on the PostControl to display the individual posts.

Question: How do I get the individual post (from the binding of the posts control) into the viewModel of the PostControl?

I used a DataContext on the PostControl definition:

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

which seems to work, but I need access to the individual Post bound to this control by the parent ListBox. How can I pass the individual post into the PostControls' viewmodels?

Upvotes: 2

Views: 558

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273274

Without seeing your UserCtl it's hard to say what goes wrong, but I would say your ListBox looks OK, and each Control should be bound to an element of Posts.

What you should not do is override that in the UserCtl, so I think that DataContext="..." attribute should simply go.

Assuming that Posts is a list of PostControlViewModel that is. If it is a list of the (Business) Model Post class, you need a converter. But it should contain ViewModels.

Upvotes: 1

Related Questions