DataGrid 内嵌ComboBox动态数据联动
在DataGrid的单元格中嵌入ComboBox是十分常见且是经常使用的一个操作。在上一篇中,我为大家介绍了如何使用静态资源绑定作为ComboBox的数据源。然而,在实际开发的过程中,我们经常会碰到处理动态数据的问题。本文将为大家介绍如何动态绑定DataGrid中ComboBox的数据源。
准备工作
1)测试项目的建立
请参考我的Silverlight-a-powerful-DataGrid-component-2-data-exchange-of-the-ADO.NET-Entity-Framework">强大的DataGrid组件[2]_数据交互之ADO.NET Entity Framework——Silverlight学习笔记[10]。
2)创建测试用数据库
为了实现数据联动,我们需要在测试数据库Employees中创建如下的两张数据表。(使用SQL Server">SQL Server Express创建)
两表的字段属性:
[Employee]
[Department]
关系图:
创建Linq to SQL数据模型
具体步骤参照我的强大的DataGrid组件[3]_数据交互之Linq to SQL——Silverlight学习笔记[11]。
下面是EmployeeModel.dbml图
建立Silverlight-enabled WCF Web Service
具体步骤参照我的强大的DataGrid组件[3]_数据交互之Linq to SQL——Silverlight学习笔记[11]。
我们需要建立如下的两个Silverlight-enabled WCF Web Service。
EmployeesInfoSevice.svc.cs代码如下:
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
using EmployeesContext;//引入数据库实体所在命名空间
using EmployeesEntities;//引入数据表实体所在命名空间
namespace DataGridnComboBox
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EmployeesInfoSevice
{
[OperationContract]
public List<Departments> GetEmployeesDepartment()
{
EmployeeModelDataContext db = new EmployeeModelDataContext();
return db.Departments.ToList();
}
// Add more operations here and mark them with [OperationContract]
}
}
EmployeesInfo2Sevice.svc.cs代码如下:
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
using EmployeesContext;//引入数据库实体所在命名空间
using EmployeesEntities;//引入数据表实体所在命名空间
namespace DataGridnComboBox
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EmployeesInfo2Service
{
[OperationContract]
public List<Employees> GetEmployeesInfo(int departmentid)
{
EmployeeModelDataContext db = new EmployeeModelDataContext();
return db.Employees.Where(x => x.DepartmentID == departmentid).ToList();
}
// Add more operations here and mark them with [OperationContract]
}
}
建立完成按Ctrl+Shift+B进行编译。
创建SilverlightClient界面及组件代码
MainPage.xaml代码:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" xmlns:dataInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input" xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="SilverlightClient.MainPage"
d:DesignWidth="320" d:DesignHeight="240">
<Grid x:Name="LayoutRoot" Width="320" Height="240" Background="White">
<dataInput:Label Height="20" HorizontalAlignment="Left" Margin="8,12,0,0" VerticalAlignment="Top" Width="43" FontSize="16" Content="部门:"/>
<ComboBox x:Name="cbDepartment" Height="32" HorizontalAlignment="Left" Margin="59,6,0,0" VerticalAlignment="Top" Width="137" FontSize="14"/>
<data:DataGrid x:Name="dgFilter" AutoGenerateColumns="False" HorizontalAlignment="Left" Margin="8,60,0,57" Width="267" FontSize="14">
<data:DataGrid.Columns>
<data:DataGridTemplateColumn Header="查询姓名" Width="100">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding EmployeeName}"></TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
<data:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox x:Name="CB" Loaded="CB_Loaded" Width="100" SelectedItem="{Binding EmployeeName,Mode=TwoWay}" /><!--注意:这里是实施动态联动的关键-->
</DataTemplate>
</data:DataGridTemplateColumn.CellEditingTemplate>
</data:DataGridTemplateColumn>
</data:DataGrid.Columns>
</data:DataGrid>
</Grid>
</UserControl>
MainPage.xaml.cs代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Data.Services.Client;
using SilverlightClient.EmployeesInfoWCFService;
using SilverlightClient.EmployeesInfo2WCFService;
namespace SilverlightClient
{
public partial class MainPage : UserControl
{
List<Employees> cbCBListProvider = new List<Employees>();
List<string> cbCBContent = new List<string>();
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
this.cbDepartment.SelectionChanged += new SelectionChangedEventHandler(cbDepartment_SelectionChanged);
}
void cbDepartment_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (cbDepartment.SelectedItem != null)
{
int departmentid = ((Departments)cbDepartment.SelectedItem).DepartmentID;
EmployeesInfo2ServiceClient webClient = new EmployeesInfo2ServiceClient();
webClient.GetEmployeesInfoAsync(departmentid);
webClient.GetEmployeesInfoCompleted +=
new EventHandler<GetEmployeesInfoCompletedEventArgs>(webClient_GetEmployeesInfoCompleted);
}
}
void webClient_GetEmployeesInfoCompleted(object sender, GetEmployeesInfoCompletedEventArgs e)
{
cbCBListProvider = e.Result.ToList<Employees>();
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
//示例数据
List<Employees> em = new List<Employees>();
em.Add(new Employees() { EmployeeName = "张三" });
em.Add(new Employees() { EmployeeName = "李四" });
dgFilter.ItemsSource = em;
EmployeesInfoSeviceClient webClient = new EmployeesInfoSeviceClient();
webClient.GetEmployeesDepartmentAsync();
webClient.GetEmployeesDepartmentCompleted +=
new EventHandler<GetEmployeesDepartmentCompletedEventArgs>(webClient_GetEmployeesDepartmentCompleted);
}
void webClient_GetEmployeesDepartmentCompleted(object sender, GetEmployeesDepartmentCompletedEventArgs e)
{
cbDepartment.ItemsSource = e.Result;
cbDepartment.DisplayMemberPath = "DepartmentName";
}
void CB_Loaded(object sender, RoutedEventArgs e)//处理dgFilter加载的ComboBox的数据源
{
ComboBox curComboBox = sender as ComboBox;
cbCBContent.Clear();
cbCBListProvider.ForEach(x => cbCBContent.Add(x.EmployeeName));
curComboBox.ItemsSource = cbCBContent;
}
}
}
最终效果图