Bind button in DataTemplate to command in the form’s ViewModel

It’s:

{Binding DataContext.FireCommand,
         RelativeSource={RelativeSource AncestorType=ListBox}}

No need to walk up to the root unless you actually change the DataContext along the way, but as the ListBox seems to bind to a property on the main VM this should be enough.

The only thing i recommend reading is the Data Binding Overview, and the Binding class documentation (including its properties).


Also here is a short explanation on how bindings are constructed: A binding consists of a source and a Path relative to that source, by default the source is the current DataContext. Sources that can be set explicitly are: Source, ElementName & RelativeSource. Setting any of those will override the DataContext as source.

So if you use a source like RelativeSource and want to access something in the DataContext on that level the DataContext needs to appear in the Path.

Leave a Comment