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}" />
CommandParameter keeps the plain binding so the clicked item is passed along.
Where it stops working
-
ElementNamealso works inside aDataTemplatein WPF, but ties the template to one view. - Inside a
ContextMenuorToolTip, neitherRelativeSourcenorElementNamereaches the window, because the popup is outside its element tree. Put the parentDataContextin the owner'sTag, then readPlacementTarget.Tagfrom the menu.
A Japanese version is also available.
Related Articles
- Reading WPF Binding Errors and Diagnosing Them with the Output Window
- Selecting and Expanding a WPF TreeView Node from Code, and Why SelectedItem Is Read-Only
- Fixing a RelayCommand Whose CanExecute Does Not Update the Button State in WPF
- Binding to a WPF UserControl's Own Dependency Property from Inside the Control
- Switching Controls Between Display and Edit Modes in WPF DataGrid Cells
- WPF ComboBox ItemsSource Binding Patterns and Selected Value Retrieval
- TreeView | WPF Standard Control Demo App (.NET 10)
- ListBox | WPF Standard Control Demo App (.NET 10)
Top comments (0)