标签:style blog http color io os ar strong sp
文章概述:本演示介绍如何在WPF的MVVM框架中,通过数据绑定的方式获取下拉列表中的选中项。程序运行后的效果如下图所示:
温馨提示:如果屏幕录像和代码不能正常下载,可站内留言,或发邮件到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>
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new MainWindowModel(); } }
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); } } }
public class Company { public string CompanyName { get; set; } public string Address { get; set; } }
private void ShowSelectedCompanyHandler(object sender, DelegateCommandEventArgs e) { MessageBox.Show(this.CurrentCompany.CompanyName); }
标签:style blog http color io os ar strong sp
原文地址:http://blog.csdn.net/gjysk/article/details/40407287