&tag(WPF/ComboBox); *目次 [#l3c59fb0] #contents *参考情報 [#k208d87b] *プロパティ [#a24e9b88] -同じような名前のプロパティがあって混乱するのでまとめ。 -ComboBoxにカスタムオブジェクトを設定している場合を考える(例Animalクラスのオブジェクト)。 **DisplayMemberPath [#eda0ad05] -コンボボックスに表示するオブジェクトのプロパティ名。 -例)AnimalクラスのNameプロパティ。 DisplayMemberPath="Name" **SelectedItem [#a2602574] -コンボボックスで選択されたオブジェクトを設定するのに使う -例)選択されたAnimalオブジェクトをViewModelにセット SelectedItem="{Binding SelectedAnimal}" **SelectedValuePath [#q4e767fb] -コンボボックスで選択されたオブジェクトのプロパティを取り出すのに使う。 -例)選択されたAnimalオブジェクトのNameプロパティを取り出す。 SelectedValuePath="{Binding Name}" **SelectedValue [#ne76324e] -コンボボックスで選択されたオブジェクトの値の設定先を指定。SelectedValuePathといっしょに使うことが多いのかな。 -例)選択されたAnimalオブジェクトのNameプロパティをViewModelのAnimalNameプロパティに設定する。 SelectedValuePath="{Binding Name}" SelectedValue="{Binding AnimalName}" *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; } }}