Silverlight 4 DataGrid动态生成列及绑定数据

转载 2012年05月15日 10:36:34

原文地址:http://hi.baidu.com/wutaof509/blog/item/d5306512500ad01db8127b47.html

补充:  AutoGenerateColumns - 是否根据数据源自动生成列
    RowDetailsVisibilityMode - 显示相应的行的详细数据时所使用的显示模式
    DataGrid.Columns - 手工定义DataGrid的列
    DataGrid.RowDetailsTemplate - 用于显示相应的行的详细数据的模板
    AreRowDetailsFrozen - 是否冻结 RowDetailsTemplate
    GridLinesVisibility - 表格分隔线的显示方式
    RowBackground - 奇数数据行背景
    AlternatingRowBackground - 偶数数据行背景
    IsReadOnly - 单元格是否只读
    FrozenColumnCount - 表格所冻结的列的总数(从左边开始数)
    SelectionMode - 行的选中模式
    CanUserReorderColumns - 是否允许拖动列
    CanUserResizeColumns - 是否允许改变列的宽度
    CanUserSortColumns - 是否允许列的排序
    VerticalGridLinesBrush - 改变表格的垂直分隔线的 Brush
    HorizontalGridLinesBrush - 改变表格的水平分隔线的 Brush
    HeadersVisibility - 表头(包括列头和行头)的显示方式

This process is pretty straight forward, so instead of doing the usual end-to-end walk through, I'm going to provide you with a Rosetta Stone between the static XAML form and the dynamic C#/VB form for the scenario in the last post.
Defining a DataGrid

For any of these columns to be useful you are going to first need a DataGrid to add them to.  The following creates a DataGrid, adds it as a child of the root layout Grid, and sets its ItemsSource to a collection called "source".

C#

DataGrid targetDataGrid = new DataGrid();
targetDataGrid.ItemsSource = source;
LayoutRoot.Children.Add(targetDataGrid);

C#

using System.Windows.Data;

...

DataGridTextBoxColumn textBoxColumn = new DataGridTextBoxColumn();
textBoxColumn.Header = "First Name";
textBoxColumn.DisplayMemberBinding = new Binding("FirstName");
targetDataGrid.Columns.Add(textBoxColumn);


C#

using System.Windows.Data;

...

DataGridCheckBoxColumn checkBoxColumn = new DataGridCheckBoxColumn();
checkBoxColumn.Header = "Available";
checkBoxColumn.DisplayMemberBinding = new Binding("Available");
targetDataGrid.Columns.Add(checkBoxColumn);



Defining a DataGrid Template Column

The following creates a DataGridTemplateColumn bound to the Birthday property with a header of "Birthday", and adds it to the columns collection of the DataGrid named "targetDataGrid".
Static

<UserControl.Resources>
<local:DateTimeConverter x:Key="DateConverter" />
</UserControl.Resources>

...

<my:DataGrid x:Name="targetDataGrid" AutoGenerateColumns="False" >
<my:DataGrid.Columns>
<my:DataGridTemplateColumn Header="Birthday">
<my:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Text="{Binding Birthday,
Converter={StaticResource DateConverter}}"
FontFamily="Trebuchet MS" FontSize="11"
Margin="5,4,5,4"/>
</DataTemplate>
</my:DataGridTemplateColumn.CellTemplate>
<my:DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<DatePicker
SelectedDate="{Binding Birthday, Mode=TwoWay}" />
</DataTemplate>
</my:DataGridTemplateColumn.CellEditingTemplate>
</my:DataGridTemplateColumn>
</my:DataGrid.Columns>
</my:DataGrid>

Dynamic

There are two ways to dynamically create a template column for a DataGrid.  One is to load in the CellTemplate and CellEditingTemplates as DataTemplates from resources, and the other is to construct the DataTemplates on the fly using XamlReader.

1. Resources Method

This method creates the CellTemplate DataTemplate and the CellEditingTemplate DataTemplate in XAML and stores them as named resources.  Then when the column is created the DataTemplates are used.

Use the below XAML to create the DataTemplates as resources to support the code for this method.

<UserControl.Resources>
<local:DateTimeConverter x:Key="DateConverter" />
<DataTemplate x:Key="myCellTemplate">
<TextBlock
Text="{Binding Birthday,
Converter={StaticResource DateConverter}}"
FontFamily="Trebuchet MS" FontSize="11"
Margin="5,4,5,4"/>
</DataTemplate>
<DataTemplate x:Key="myCellEditingTemplate">
<DatePicker
SelectedDate="{Binding Birthday, Mode=TwoWay}" />
</DataTemplate>
</UserControl.Resources>

C#

using System.Windows.Data;

...

DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header = "Birthday";
templateColumn.CellTemplate = (DataTemplate)Resources["myCellTemplate"];
templateColumn.CellEditingTemplate =
(DataTemplate)Resources["myCellEditingTemplate"];
targetDataGrid.Columns.Add(templateColumn);

2. XamlReader Method

This method creates the DataTemplate inline using the XamlReader class.  This class takes a string and parses it to try to build a visual tree.  In this case we are creating DataTemplates.  This method is especially useful if the DataTemplate itself has to be dynamic.  One example being if you wanted to modify what the element in the template was data bound to.

Warning: This method is considerably more difficult than the resources method.  I recommend only using this if you need to dynamically create the DataTemplate.

Some things to watch out for:

1. You will need to declare any XAML namespace that is used in the data template
2. Any custom XAML namespace needs to specify both the clr-namespace and the assembly
3. You cannot have white space between the xmlns: and the name of your namespace
4. External resources cannot be referenced, they need to be declared inline
5. The entire template is a single line, so if you get a XAML Parse exception, it will always say line 1, however the character is fairly accurate if you were to concatenate all of your lines.
6. When using the StringBuilder approach shown below, make sure that you have the correct white space at the end of a line so that it is correctly separated when concatenated with the next line.

Now that the warnings are out of the way, here is how you do the equivalent of the code above:

C#

using System.Windows.Data;
using System.Windows.Markup;
using System.Text;

...

DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
templateColumn.Header = "Birthday";
StringBuilder CellTemp = new StringBuilder();
CellTemp.Append("<DataTemplate ");
CellTemp.Append("xmlns='http://schemas.microsoft.com/client/2007' ");
CellTemp.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
//Be sure to replace "YourNamespace" and "YourAssembly" with your app's
//actual namespace and assembly here
CellTemp.Append("xmlns:local = 'clr-namespace:YourNamespace");
CellTemp.Append(";assembly=YourAssembly'>");
CellTemp.Append("<Grid>");
CellTemp.Append("<Grid.Resources>");
CellTemp.Append("<local:DateTimeConverter x:Key='DateConverter' />");
CellTemp.Append("</Grid.Resources>");
CellTemp.Append("<TextBlock ");
CellTemp.Append("Text = '{Binding Birthday, ");
CellTemp.Append("Converter={StaticResource DateConverter}}' ");
CellTemp.Append("FontFamily='Trebuchet MS' FontSize='11' ");
CellTemp.Append("Margin='5,4,5,4'/>");
CellTemp.Append("</Grid>");
CellTemp.Append("</DataTemplate>");
StringBuilder CellETemp = new StringBuilder();
CellETemp.Append("<DataTemplate ");
CellETemp.Append("xmlns='http://schemas.microsoft.com/client/2007' ");
CellETemp.Append("xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>");
CellETemp.Append("<DatePicker ");
CellETemp.Append("SelectedDate='{Binding Birthday, Mode=TwoWay}' />");
CellETemp.Append("</DataTemplate>");
templateColumn.CellTemplate =
(DataTemplate)XamlReader.Load(CellTemp.ToString());
templateColumn.CellEditingTemplate =
(DataTemplate)XamlReader.Load(CellETemp.ToString());
targetDataGrid.Columns.Add(templateColumn);

EasyUI_datagrid实现动态加载列并为其绑定数据

最近项目中遇到了这么一个需求,在datagrid中显示的数据需要动态的加载,也就是说表格中显示的列是不固 定的,显示的列的名称和列的数量都是不固定的,这些数据都是需要我们从后台拿来数据然后在动态的绑...
  • u013045437
  • u013045437
  • 2016年03月06日 23:24
  • 4691

datagrid动态加载列(续)

之前有一篇博客写到了如何动态加载datagrid的列,上次只是介绍如何动态动态表头,并没有将数据添加到datagrid中,本次主要来说如何将数据库中的数据,动态添加到每一列中。      先说一下为...
  • u013038643
  • u013038643
  • 2016年04月24日 17:25
  • 1377

silverlight根据json字符串动态创建实体类

1、接收json字符串: //用JsonValue转换json字符串是为了之后获得json字符串的每行数据和每一列的列名 JsonValue jv = JsonValue.Parse(json);...
  • mutou965175859
  • mutou965175859
  • 2015年07月10日 13:22
  • 1654

WPF-DataGrid后台动态生成列

DataGrid后台动态生成列 Now that you know the basics of the Silverlight DataGrid and how to specify...
  • yqj234
  • yqj234
  • 2016年03月14日 15:49
  • 4950

Easyui DataGrid动态生成列

 一、DataGrid基本定义 1、HTML Page [html] view plaincopyprint? body>       table id="myList...
  • liuchuan__________
  • liuchuan__________
  • 2015年09月17日 17:14
  • 8991

【datagrid】动态加载列

之前我们的项目在前台显示只需要把数据从数据库读出来进行显示就可以,datagrid的表头字段都是写死的,把数据往表里一扔,就基本没什么事儿了,结果客户前几天要求,其中一个字段不能是死的,应该是有多少项...
  • u013036688
  • u013036688
  • 2016年01月03日 16:32
  • 3161

WPF中DataGrid使用自定义列绑定数据

WPF中DataGrid使用自定义列绑定数据
  • hit_why
  • hit_why
  • 2017年03月24日 14:24
  • 2733

数据绑定——DataGrid

绑定数据
  • wgp15732622312
  • wgp15732622312
  • 2016年05月15日 17:14
  • 510

easyui之datagrid动态修改列

easyui datagrid 定义列的方式通常是: $('#grid').datagrid({columns:[[ {field:'f1',title:'字段1',width:160}...
  • liuxiao723846
  • liuxiao723846
  • 2015年08月28日 15:12
  • 2954

【.Net码农】DataGrid 数据绑定使用小结一

DataGrid 数据绑定使用小结   做过ASP.NET开发的朋友都知道,ASP.NET提供了强大的列表数据控件,从ASP.NET1.1 时代的DataGrid,到ASP.NET2.0时...
  • CrackLibby
  • CrackLibby
  • 2014年10月29日 17:42
  • 1692
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Silverlight 4 DataGrid动态生成列及绑定数据
举报原因:
原因补充:

(最多只允许输入30个字)