ComboBox控件 下拉列表

数据类:

    public class People
    {
        private string _name = "";
        private int _age = 0;

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
            }
        }
        public int Age
        {
            get { return _age; }
            set
            {
                _age = value;
            }
        }
    }

前台xaml

        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <ComboBox x:Name="comboBox" Width="120" SelectionChanged="comboBox_SelectionChanged"/>
        </StackPanel>

后台cs

       private void Init()
        {
            List<People> peoples = new List<People>();
            for(int i=0;i<5;i++)
            {
                People p = new People();
                p.Name = "姓名" + i;
                p.Age = 15 + i;
                peoples.Add(p);
            }
            comboBox.ItemsSource = peoples;
            comboBox.DisplayMemberPath = "Name";//显示字段
            comboBox.SelectedValuePath = "Age";//选中后,对应comboBox.SelectedValue属性的值 
            comboBox.SelectedIndex = 0;
        }

        private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int age = (int)comboBox.SelectedValue;
            Console.WriteLine("age:{0}", age);
        }

猜你喜欢

转载自blog.csdn.net/i1tws/article/details/80525040