&tag(WPF/ComboBox); *目次 [#l3c59fb0] #contents *参考情報 [#k208d87b] *ComboBoxにカスタムオブジェクトを設定する例 [#a9fe22ce] **概要 [#o1aedffd] -ViewModelにAnimaのリストを持ち画面に表示。 -ComboBoxに表示するのはAnimalのNameプロパティ。 -ViewModelに設定するのは選択されたAnimalのIdプロパティ。 **XAML [#v0e3726c] #pre{{ <ComboBox ItemsSource="{Binding Animals}" SelectedItem="{Binding Animal}" DisplayMemberPath="Name" SelectedValuePath="Id" SelectedValue="{Binding AnimalId}" /> <Button Click="Button_Click">検証</Button> }} **Animal.cs [#aadecb3f] #pre{{ public class Animal { public int Id { get; set; } public string Name { get; set; } public override string ToString() { return string.Format("{0} {1}", Id, Name); } } }} **ViewModel.cs [#o1a4ed7a] #pre{{ public class SimpleComboBox2WindowViewModel :INotifyPropertyChanged { public SimpleComboBox2WindowViewModel() { this.Animals = new ObservableCollection<Animal>() { new Animal() {Id = 1, Name="ゾウ"}, new Animal() {Id = 2, Name="ライオン"}, new Animal() {Id = 3, Name="トラ"}, }; this.animalId = 2; } public ObservableCollection<Animal> Animals { get; set; } private int animalId; public int AnimalId { get { return animalId; } set { if (animalId != value) { animalId = value; this.NotifyPropertyChanged("AnimalId"); } } } public void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public event PropertyChangedEventHandler PropertyChanged; } }}