本演示介绍如何在WPF的MVVM框架中,通过数据绑定的方式获取下拉列表中的选中项。程序运行后的效果如下图所示:
在线播放:http://v.youku.com/v_show/id_XODA5OTYzMDU2.html
温馨提示:如果屏幕录像和代码不能正常下载,可站内留言,或发邮件到524130780@QQ.COM
XAML代码如下所示:
<Window x:Class="Demo02Ex01.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="262" Width="402"> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> </Grid.ColumnDefinitions> <ComboBox Grid.Row="0" Grid.Column="0" Width="300" Height="30" ItemsSource="{Binding CompanyNames}" DisplayMemberPath="CompanyName" SelectedItem="{Binding CurrentCompany}" /> <Button Grid.Row="1" Width="100" Height="70" Content="获取选择项" Command="{Binding Path=ShowSelectedCompanyCommand}"/> </Grid> </Window>
CS代码如下所示:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new MainWindowModel(); } }
综合上述两端代码可知,和MainWindow视图管理的ViewModel类是MainWindowModel类,XAML代码中的Binding所指的成员就是该ViewModel类中的成员。比如CompanyNames和CurrentCompany都是MainWindowModel的属性。
MainViewModel类的代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; namespace Demo02Ex01.ViewModels { public class MainWindowModel { public MainWindowModel() { this.CompanyNames = new List<Company>(); this.CompanyNames.Add(new Company() { CompanyName = "中国核工业集团公司", Address = "" }); this.CompanyNames.Add(new Company() { CompanyName = "中国航科技集团公司", Address = "" }); this.CompanyNames.Add(new Company() { CompanyName = "中国电科技集团公司", Address = "" }); this.CompanyNames.Add(new Company() { CompanyName = "中国长江三峡工程发总公司", Address = "" }); this.CompanyNames.Add(new Company() { CompanyName = "中国移通信集团公司", Address = "" }); this.CurrentCompany = this.CompanyNames[1]; this.ShowSelectedCompanyCommand = new DelegateCommand(this.ShowSelectedCompanyHandler); } public List<Company> CompanyNames { get; set; } public Company CurrentCompany { get; set; } public DelegateCommand ShowSelectedCompanyCommand { get; set; } private void ShowSelectedCompanyHandler(object sender, DelegateCommandEventArgs e) { MessageBox.Show(this.CurrentCompany.CompanyName); } } }
通过为ComboBox指定DisplayMemberPath属性,可以告知程序要显示的内容。由于CompanyNames的类型是List<Company>的,因此DisplayMemberPath所指定的字符串就是Company类的CompanyName属性名。代码如下:
public class Company { public string CompanyName { get; set; } public string Address { get; set; } }
而和按钮的单击操作则是由Command属性指定的命令进行处理的,仍然是和MainWindowModel的成员ShowSelectedCompanyCommand关联绑定。这是一个自定义命令,对于当前的按钮而言,具体执行的代码如下所示:
private void ShowSelectedCompanyHandler(object sender, DelegateCommandEventArgs e) { MessageBox.Show(this.CurrentCompany.CompanyName); }
至此,通过ViewModel的CurrentCompany属性既可以修改下拉列表中的选中项,又可以在ViewModel中获取到下拉列表中的选中项。