Ivo
Ivo

Reputation: 13

MVVM View Binding

Lets say I have a list of items. So I have 2 views: ListView and ItemView.

I also have 2 ViewModels: ListViewModel and ItemViewModel.

In ListViewModel I create and initialize ObservableCollection of ItemViewModels. In ListView I have ListBox with ItemTemplate -> ItemView, and ItemSource binded to the ObservableCoolection into the ListViewModel. I want to bind each ItemView to each ItemViewModel so I will be able to use the binding into ItemView.xaml, but I cannot achive it.

Upvotes: 1

Views: 466

Answers (1)

Amit
Amit

Reputation: 256

What I understood from your question is you want to bind ItemViewModel to ItemView.xaml and your ListBox resides in some other xaml(say ListBox.xaml). You don't want to apply binding related to ItemViewmodel and ItemVIew in ListBox.xaml. If this was the issue, you can easily create a DataTemplate mapping to achieve so:

<Window
    xmlns:vw="namespace of your view files (i.e. xaml files. ListBox.xaml and ItemView.xaml)"
    xmlns:ViewModels="namespace of your view model files (i.e. ItemViewModel.cs, ListBoxViewModel.cs)">
    <Window.Resources>
        <DataTemplate DataType="{x:Type ViewModels:ItemViewModel}">
                <vw:ItemView />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Path=List of ItemViewmodel in ListBoxViewModel.cs}"
    </Grid>
</Window>

Then, you ItemViewModel class will be mapped with ItemView as it is specified in Resources without any key. Now you can apply binding in ItemView.xaml. Look, you do not need to assign Itemtemplate of ListBox here, that will be resolved automatically. If you want to specify the ItemTemplate anyway (and do not want to specify in resource), then write this:

<ListBox.ItemTemplate>
    <DataTemplate>
        <vw:ItemView />
    </DataTemplate>
</ListBox.ItemTemplate>

Either way should work :)

Upvotes: 2

Related Questions