Commanding within DataTemplates in MVVM!

A quick post about setting commands within DataTemplates when using the MVVM pattern!

When you are inside a DataTemplate the DataContext is changed to the  the current item, so to access the command you will need to use the “relative source”

Something like

 <Button Content="Delete" Width="Auto" 
Command="{Binding DataContext.RemoveCommand, 
RelativeSource={RelativeSource FindAncestor,
 AncestorType={x:Type ItemsControl}}}" 
CommandParameter="{Binding}">

Hope this real quick note helps save you some time!!

Until next time!

Cennest!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>