效果如下图:
1. 建立数据模型类
public class Book
{
public string Name { get; set; }
public string ISBN { get; set; }
}
2. 创建模型的数据集合
List<Book> books = new List<Book>();
books.Add(new Book { Name = "C# 7.0", ISBN = "123-45" });
books.Add(new Book { Name = "Python ", ISBN = "678-901" });
books.Add(new Book { Name = "SQL Server", ISBN = "22-888" });
books.Add(new Book { Name = "Linux", ISBN = "662-999" });
3. 绑定数据到ComboBox对象
cboBindingMode.ItemsSource = books;
cboBindingMode.DisplayMemberPath = "Name";//设置显示属性
cboBindingMode.SelectedValuePath = "ISBN";//设置选择属性
4. 测试所选择的值
将文本显示Text绑定到ComboBox
<TextBox x:Name="txtBindingSelectedItem" Text="{Binding ElementName=cboBindingMode,Path=SelectedValue}"></TextBox>
事件的方式
在ComboBox中添加事件
<ComboBox x:Name="cboBindingMode" Margin=" 2" SelectionChanged="cboBindingMode_SelectionChanged"></ComboBox>
在事件中将选择的Item的值赋值给另一个文本框
private void cboBindingMode_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
txtSeletcedMode.Text = cboBindingMode.SelectedValue.ToString();
}
2中方式一样效果,绑定更加简洁和方便。