次のWPFDataGrid+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
}
これで、希望する結果は、 Houseタイプの行のリストを表示するDataGridであり、列の1つに、ユーザーがHouse.HouseOwnerの値を変更できるComboBoxがあります。
このシナリオでは、グリッドのDataContextはViewModel.Housesであり、ComboBoxの場合、ItemsSourceをViewModel.Ownersにバインドする必要があります。
これも可能ですか?私はこれに頭を悩ませています...私ができる最善のことは、ItemsSourceを正しくバインドすることですが、ComboBox(DataGridTemplateColumn内)は各行にHouse.HouseOwnerの正しい値を表示していません。
注:ComboBoxを画像から取り出し、代わりにTextBlockをDataTemplateに配置すると、各行の値を正しく表示できますが、ItemsSourceの両方を取得し、選択範囲に正しい値を表示することはできません。 ..。。
コードビハインド内で、ウィンドウの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>
これについての助けが欲しいです...しかし、少しのブードゥーが必要なようです...