Articles in categories

Articles

Binding from DataTemplate (DataGrid)

Today I was struggling to get a Command binding to work from within a DataTemplate in the DataGrid.

The ItemsSource was set to a list of objects and each object was shown in a DataGrid column. At the beginning of each row there is an Save and Delete button added. The buttons were added through a DataTemplate.

        <DataGridTemplateColumn>
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <Button Visibility="Visible"
                      IsEnabled="True"
                      Content="Save"
                      Command="{Binding SaveProductWysiwygCommand}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

But the Command didn't work, it wasn't even called.
The reason for this is that the datacontext for the DataGrid is set to the ItemsSource. And since the ItemsSource pointed to the list of objects the command wasn't found. The ItemsSource is a DependencyProperty in my ViewModel, so I needed to search on a higher level for the correct DataContext (my VM).

Below the solution that worked for me, setting the RelativeSource to the UserControl and use the UserControl's DataContext to get the correct Command:

Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},
Path=DataContext.SaveProductWysiwygCommand}"

The explanation made sense but it took a while before I found the correct way of handling this so that it would work. In this case it was a Command binding, but the same should work for any binding.

Article is a note to self as it won't be the last time I need to do this..