0
votes

I'm currently trying to do some binding inside of a datagrid but I'm having problems getting up to the level of DataContext of the view.

Here is the code:

<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox SelectedItem="{Binding Operators}"
ItemsSource="{Binding DataContext.OperatorList,ElementName=FilterGrid}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

Any ideas on whats wrong? The View's Viewmodel is connected in the code behind.

EDIT: The Binding that is not working is the ItemsSource binding shown above

1

1 Answers

3
votes

When you use the DataTemplate of the DataGrid, you cannot use ElementName bindings as it won't resolve properly due to limitations in the resolution capabilities of FindControl within the DataGrid control hierarchy. You need to use a RelativeSource binding that travels up the control tree looking for a specific control type (which you need to determine - from your element name I assumed it was a DataGrid ancestor type).

 <DataGridTemplateColumn.CellEditingTemplate>
   <DataTemplate>
     <ComboBox 
        SelectedItem="{Binding Operators}" 
        ItemsSource="{Binding DataContext.OperatorList, 
                      RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
      />
   </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

See this SO post that shares some potentially related sample code using MVVM to access the DataContext of the UserControl host to populate a ComboBox ItemsSource.