Tag: WPF/ComboBox
DisplayMemberPath="Name"
SelectedItem="{Binding SelectedAnimal}"
SelectedValuePath="{Binding Name}"
SelectedValuePath="{Binding Name}" SelectedValue="{Binding AnimalName}"
<ComboBox ItemsSource="{Binding Animals}" SelectedItem="{Binding Animal}" DisplayMemberPath="Name" SelectedValuePath="Id" SelectedValue="{Binding AnimalId}" /> <Button Click="Button_Click">検証</Button>
public class Animal { public int Id { get; set; } public string Name { get; set; } public override string ToString() { return string.Format("{0} {1}", Id, Name); } }
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; }