DEV Community

Cover image for Binding to the Parent DataContext from Inside a WPF DataTemplate
s-iguchi09
s-iguchi09

Posted on Edited on Originally published at s-iguchi09.github.io AI-assisted

Binding to the Parent DataContext from Inside a WPF DataTemplate

Each row of an ItemsControl has a Delete button bound to {Binding DeleteCommand}. The button looks enabled, but clicking it does nothing. The command lives on the parent view model, while everything inside the template gets the row item as its DataContext.

This is a short summary. The full article, with a table per binding style and measurements inside ContextMenu and ToolTip on .NET 10, is here:
Binding to the Parent DataContext from Inside a WPF DataTemplate

Why nothing looks wrong

When the binding fails, Command stays null. A null command leaves IsEnabled at True, so the screen gives no hint. The Output window does: its DataItem names the item type instead of the view model.

The fix

Walk up to the ItemsControl and go through its DataContext:

<Button Content="Delete"
        Command="{Binding DataContext.DeleteCommand,
                  RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
        CommandParameter="{Binding}" />
Enter fullscreen mode Exit fullscreen mode

CommandParameter keeps the plain binding so the clicked item is passed along.

Where it stops working

  • ElementName also works inside a DataTemplate in WPF, but ties the template to one view.
  • Inside a ContextMenu or ToolTip, neither RelativeSource nor ElementName reaches the window, because the popup is outside its element tree. Put the parent DataContext in the owner's Tag, then read PlacementTarget.Tag from the menu.

A Japanese version is also available.

Related Articles

Top comments (0)