2012-12-13 71 views
2

我有一個DataGrid,它有一個DataGridTemplateColumn,它使用DataGrid的ItemsSource綁定,但是在DataGridTemplateColumn的ComboBox中,我希望能夠綁定到視圖的ViewModel而不是ItemsSource。如何使用RelativeSource綁定創建DataGrid綁定到Model和ViewModel?

<DataGrid ItemsSource="{Binding ModelValues, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" > 
     <DataGridTemplateColumn Header="myHeader" Width="200"> 
      <DataGridTemplateColumn.CellTemplate> 
       <DataTemplate> 
        <ComboBox DisplayMemberPath="Value" SelectedValuePath="Key" IsEnabled="False" 
          SelectedValue="{Binding myID, Mode=TwoWay}" 
          ItemsSource="{Binding Path=myList, 
          RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:ViewModel}}}" /> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellTemplate> 
      <DataGridTemplateColumn.CellEditingTemplate> 
       <DataTemplate> 
        <ComboBox DisplayMemberPath="Value" SelectedValuePath="Key" IsEnabled="False" 
          SelectedValue="{Binding myID, Mode=TwoWay}" 
          ItemsSource="{Binding Path=myList, 
          RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:ViewModel}}}" /> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellEditingTemplate> 
     </DataGridTemplateColumn> 
</DataGrid> 

視圖模型具有ModelValues財產所有權以及myList財產。 ModelValues用於DataGridItemsSource,我想用myList代替ComboBoxItemsSource

我該如何更改我的RelativeSource命令,以便它能正常工作?

回答

5

綁定到網格的的datacontext:

<DataGrid ItemsSource="{Binding ModelValues, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" > 
     <DataGridTemplateColumn Header="myHeader" Width="200"> 
      <DataGridTemplateColumn.CellTemplate> 
       <DataTemplate> 
        <ComboBox DisplayMemberPath="Value" SelectedValuePath="Key" IsEnabled="False" 
          SelectedValue="{Binding myID, Mode=TwoWay}" 
          ItemsSource="{Binding Path=DataContext.myList, 
          RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" /> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellTemplate> 
      <DataGridTemplateColumn.CellEditingTemplate> 
       <DataTemplate> 
        <ComboBox DisplayMemberPath="Value" SelectedValuePath="Key" IsEnabled="False" 
          SelectedValue="{Binding myID, Mode=TwoWay}" 
          ItemsSource="{Binding Path=DataContext.myList, 
          RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" /> 
       </DataTemplate> 
      </DataGridTemplateColumn.CellEditingTemplate> 
     </DataGridTemplateColumn> 
</DataGrid>