我有一个DataGrid,它有一个DataGridTemplateColumn,它使用DataGrid的ItemsSource绑定,但是在DataGridTemplateColumn的ComboBox中,我希望能够绑定到View的ViewModel而不是ItemsSource。
<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
用于ItemsSource
的{{1}},我想DataGrid
用于myList
ComboBox
。
如何更改ItemsSource
命令以使其正常工作?
答案 0 :(得分:6)
绑定到网格的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>