3

我有一个 DataGrid,它有一个使用 DataGrid 的 ItemsSource 绑定的 DataGridTemplateColumn,但是在 DataGridTemplateColumn 的 ComboBox 中,我希望能够绑定到 View 而不是 ItemsSource 的 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>

ViewModel 具有ModelValues属性和myList属性。ModelValues用于 的,ItemsSourceDataGridmyList用于ComboBox ItemsSource

我将如何更改我的RelativeSource命令以使其正常工作?

4

1 回答 1

7

绑定到网格的数据上下文:

<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>
于 2012-12-13T15:49:00.970 回答