C#后台绑定ComboBox
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication2 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<Person> list = new List<Person>() { new Person{Id=1,Name="张三",Sex="男"}, new Person{Id=2,Name="李四",Sex="男"}, new Person{Id=3,Name="王五",Sex="女"}, new Person{Id=4,Name="赵六",Sex="男"}, new Person{Id=5,Name="孙七",Sex="女"} }; cb.ItemsSource=list; cb.SelectedIndex = 0; } private void Button_Click(object sender, RoutedEventArgs e) { if (cb.SelectedItem != null) { Person p = cb.SelectedItem as Person; MessageBox.Show("Id:"+p.Id.ToString()+",姓名:"+p.Name+",性别:"+p.Sex); } } } public class Person { private int id; public int Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string sex; public string Sex { get { return sex; } set { sex = value; } } } }
XAML
<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <StackPanel> <ComboBox x:Name="cb" DisplayMemberPath="Name"/> <Button Content="Show" Click="Button_Click" /> </StackPanel> </Grid> </Window>
运行效果:
点击“Show”按钮,弹框显示下拉框选中项的详细信息: