work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

WPF 控件使用之ComboBox

Posted on 2011-11-23 10:38  work hard work smart  阅读(7424)  评论(0编辑  收藏  举报

下面是ComboBox的简单实用

XAML:

   <Grid>
        <ComboBox Height="23" Margin="12,12,0,0" Name="comboBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="120" />
        <Button Height="23" Margin="21,53,69,0" Name="button1" VerticalAlignment="Top" Click="button1_Click">Get ComboBox select value</Button>
    </Grid>

C# Code:

    public partial class ComboBoxTest : Window
    {
        public ComboBoxTest()
        {
            InitializeComponent();
            Bind();
        }

        public void Bind()
        {
            IList<customer> customList = new List<customer>();
            customList.Add(new customer() { ID = 3, Name = "Tom" });
            customList.Add(new customer() { ID = 4, Name = "Bob" });
            customList.Add(new customer() { ID = 5, Name = "Cat" });
            comboBox1.ItemsSource = customList;
            comboBox1.DisplayMemberPath = "Name";
            comboBox1.SelectedValuePath = "ID";
            comboBox1.SelectedValue = 4;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(comboBox1.SelectedValue.ToString());
        }
    }

    public class customer
    {
        public int ID{ get; set;}
        public string Name { get; set; }
    }