【发布时间】:2011-10-28 15:10:56
【问题描述】:
我对下面的 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>
希望对此有所帮助...不过似乎需要一点巫毒教...
【问题讨论】:
标签: wpf datagrid combobox binding datagridtemplatecolumn