Tag: WPF/ComboBox

目次

参考情報

プロパティ

DisplayMemberPath

SelectedItem

SelectedValuePath

SelectedValue

ComboBoxにカスタムオブジェクトを設定する例

概要

XAML

        <ComboBox ItemsSource="{Binding Animals}" SelectedItem="{Binding Animal}"
                    DisplayMemberPath="Name"                   
                    SelectedValuePath="Id"
                    SelectedValue="{Binding AnimalId}"
                  />
        <Button Click="Button_Click">検証</Button>

Animal.cs

    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

    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;
    }

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS