Binding DataTemplate to ViewModel

Sep 1, 2011 at 8:55 PM

Hello,

 

is there a possibility, to bind a DataTemplate to a ViewModel: When using the following DataTemplate for a ListView, the data object is bound to the ViewModel

 

<DataTemplate x:Key="ClubsItemTemplate">
    <StackPanel d:DesignWidth="363" d:DesignHeight="50" cal:Bind.Model="{Binding}">
...
    </StackPanel>
</DataTemplate>

...

<ListBox Margin="20,5,20,20" Background="{x:Null}" BorderBrush="{x:Null}"
    ItemsSource="{Binding Clubs}" 
    SelectedItem="{Binding SelectedClub}"
    ItemTemplate="{DynamicResource ClubsItemTemplate}" />

The ListBox ItemSource is bound to an ObservableCollection<Club> and so the DataTemplate is bound the a Club object.
Insteat of this, I want the DataTemplate be bound to a ClubItemViewModel or to the ViewModel in which the ListBox is located. Is this possible in any way? In this case it woul also be Ok, to make a View First Approach, but I have no idea how to solve this.

 

Thank you

Sep 1, 2011 at 11:29 PM

If I got you right (use a view located through the collection item, which is a view-model), you could benefit from this link

Sep 2, 2011 at 8:05 AM

I'm not sure if this helps for me. I've already read this yesterday, but thought, that this is not the same behaviour which I need. I will try this again later this day.

But here again my explanation (I hope a bit more precise)

The ListBox contains items of type Club, which is a POCO. When I want to add a Button to the DataTemplate, the Command of the button is not received in the ViewModel where the ListView is bound to. Instead it's possible to manage the command in the class 'Club' (the POCO class). I need a possibility to change the DataContext of the DataTemplate to another ViewModel or to the ViewModel where the ListBox is located.

I think, with the cal:Bind.Model="{Binding}", the binding is set to the object which is used in the DataTemplate. In the case the 'Club' objects.

Perhaps it's also a solution not to handle a collection of 'Club' in ClubsViewModel, but a collection of ClubItemViewModel. Then the DataTemplate would be bound to a correct ViewModel. But the solution looks a bit unattractive in my eyes.

Sep 2, 2011 at 8:22 AM

Honestly, your explanation is not so clear... :)

Is it just an issue of invoking a method on a different class? In that case you can just use the Action.TargetWithoutContext attached property.

The solution of using a view-model when needed seems legit to me, but I still cannot grasp the exact scenario, so I cannot be sure that my advice is meaningful to you.

Regarding the idea of 'swapping' the DataContext of an ItemsControl Item, every ItemsControl uses the items within its ItemsSource as DataContext for its visual children, so there is no way to swap the DataContext of the object generated by the DataTemplate. Eventually, you could use a DataTempalte containing another ContentControl, where you can specify the Bind.Model property as needed.