我对下面的 WPF DataGrid+ComboBox 场景很感兴趣。
我有一组看起来像的类;
class Owner
{
int ID { get; }
string Name { get; }
public override ToString()
{
return this.Name;
}
}
class House
{
int ID { get; }
Owner HouseOwner { get; set; }
}
class ViewModel
{
ObservableCollection<Owner> Owners;
ObservableCollection<House> Houses
}
现在我想要的结果是一个 DataGrid ,它显示了House类型的行列表,并且在其中一列中是一个 ComboBox ,它允许用户更改House.HouseOwner的值。
在这种情况下,网格的 DataContext 是ViewModel.Houses,而对于 ComboBox,我希望 ItemsSource 绑定到 ViewModel.Owners。
这甚至可能吗?我对此很感兴趣......我能做的最好的事情就是正确地绑定 ItemsSource,但是 ComboBox(在 DataGridTemplateColumn 内)没有在每一行中显示 House.HouseOwner 的正确值。
注意:如果我将 ComboBox 从图片中取出并在 DataTemplate 中放置一个 TextBlock,我可以正确查看每一行的值,但是同时获取 ItemsSource 以及在选择中显示正确的值对我不起作用...
在后面的代码中,我已将 Window上的 DataContext 设置为ViewModel,在网格上,将 DataContext 设置为ViewModel.Houses。除了这个组合框之外的所有东西,它都在工作......
我的违规列的 XAML 看起来像;
<DataGridTemplateColumn Header="HouseOwner">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=DataContext.Owners, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
DisplayMemberPath="Name"
SelectedItem="{Binding HouseOwner, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"
SelectedValue="{Binding HouseOwner.ID, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}, Mode=OneWay}"
SelectedValuePath="ID" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
希望对这个有一些帮助......不过似乎需要一点巫毒教......