我有一个 DataGrid,它有一个使用 DataGrid 的 ItemsSource 绑定(bind)的 DataGridTemplateColumn,但是在 DataGridTemplateColumn 的 ComboBox 中,我希望能够绑定(bind)到 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
用于 DataGrid
的 ItemsSource
,我想将 myList
用于 ComboBox
ItemsSource
.
如何更改我的 RelativeSource
命令以使其正常工作?
最佳答案
绑定(bind)到网格的数据上下文:
<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>
关于c# - 如何使用 RelativeSource Binding 创建 DataGrid 绑定(bind)到 Model 和 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13863408/