本文章仅为个人学习,如有错误之处请指正。
搭建WPF界面的时候,想用combobox构建一个下拉菜单,搜索的时候看到大多数都是大段代码,逻辑顺序不是很详细,摸索了大概,记录一下方便来者。
拖入combobox控件,控件的属性可以在xmal代码中更改,这里只是用了默认的代码,combobox的绑定在.cs代码中进行。
<Label Content="Label" Height="28" HorizontalAlignment="Left" Margin="12,239,0,0" Name="label8" VerticalAlignment="Top" /> <ComboBox Height="23" HorizontalAlignment="Left" Margin="130,239,0,0" Name="My_combobox" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" SelectionChanged="comboBox1_SelectionChanged" DataContext="{Binding}"></ComboBox> <TextBox Height="23" HorizontalAlignment="Left" Margin="130,301,0,0" Name="textBox8" VerticalAlignment="Top" Width="120" TextChanged="textBox8_TextChanged" />
combobox几个相关的属性:
ItemSource一般绑定list
先定义类
public class drop_down_list { public string Name { get; set; } public int ID { get; set; } public int IDS { get; set; } }
然后构建list
List<drop_down_list> Drop_down_f_g = new List<drop_down_list>(); Drop_down_f_g.Add(new drop_down_list { Name = "up_up", ID = 0, IDS = 1 }); Drop_down_f_g.Add(new drop_down_list { Name = "one_up", ID = 1, IDS = 2 }); Drop_down_f_g.Add(new drop_down_list { Name = "five_up", ID = 2, IDS = 3 }); Drop_down_f_g.Add(new drop_down_list { Name = "ten_up", ID = 3, IDS = 4 }); Drop_down_f_g.Add(new drop_down_list { Name = "fifteen_up", ID = 4, IDS = 5 }); Drop_down_f_g.Add(new drop_down_list { Name = "fifteen_down", ID = 5, IDS = 6 }); Drop_down_f_g.Add(new drop_down_list { Name = "twentyfive_up", ID = 6, IDS = 7 }); Drop_down_f_g.Add(new drop_down_list { Name = "thirty_down", ID = 7, IDS = 8 }); Drop_down_f_g.Add(new drop_down_list { Name = "fourty_down", ID = 8, IDS = 9 });
绑定combobox的数据源
My_combobox.ItemsSource = Drop_down_f_g; My_combobox.DisplayMemberPath = "Name"; My_combobox.SelectedValuePath = "IDS"; My_combobox.SelectedIndex = 0;
list的初始化和combobox我都是在mainwindow中进行的
通过comboBox的changed函数实现数据获取
private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { string test; object a; a = My_combobox.SelectedValue; test = a.ToString(); textBox8.Text = test; }
获取到name对应的ID.
交流分享,共同进步!