ComboBoxを含むカスタムDataGrid列を作成したいと思います。コンボボックスのItemSourceは列挙型にバインドされ、コンボボックスのselecteditemはコレクション要素で選択された列挙型の値にバインドされます。
これがコードです
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp"
xmlns:System="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:AnimalObservableCollection x:Key="animals">
</local:AnimalObservableCollection>
<ObjectDataProvider x:Key="animalEnum" MethodName="GetValues"
ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:AnimalType"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<DataGrid AutoGenerateColumns="False" Margin="12,12,12,101" Name="dgAnimals" CanUserAddRows="True" CanUserDeleteRows="True" DataContext="{StaticResource animals}" ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"></DataGridTextColumn>
<DataGridTemplateColumn Header="Animal type">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Source={StaticResource animalEnum}}" SelectedItem="{Binding Path=AnimalType}"></ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
コードビハインド
public partial class MainWindow : Window
{
AnimalObservableCollection animals;
public MainWindow()
{
InitializeComponent();
animals = (AnimalObservableCollection)this.FindResource("animals");
animals.Add(new Animal(AnimalType.horse,"Rex"));
}
}
public enum AnimalType { dog, cat, horse };
class AnimalObservableCollection : ObservableCollection<Animal>
{
public AnimalObservableCollection()
: base()
{
}
}
class Animal
{
private AnimalType animalType;
private string name;
public Animal()
{
}
public Animal(AnimalType animalType_, string name_)
{
animalType = animalType_;
name = name_;
}
public AnimalType AnimalType
{
get
{
return animalType;
}
set
{
animalType = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
問題は、コンボボックスがフォーカスを失うと、選択されたアイテムがDataGridのセルに表示されず、このセルが空白のままになることです。コンボボックスの選択されたアイテムを表示するためにAnimalType列にセルを作成するにはどうすればよいですか?
DataGridComboBoxColumnを使用すると完全に機能しますが、将来的にはDataGridTemplateColumnを使用していくつかの機能を追加したいと思います。