Silverlight utility tip series: 10. dynamically generate the DataGrid and dynamically bind the DataGrid template column [with instance source code]

Source: Internet
Author: User
In the previous section, we may encounter custom XML template fields in actual projects. Based on the fields in this template, the values of corresponding fields are displayed in the DataGrid. In this case
Use XmlReader to parse the fields in the Custom XML template, dynamically generate an object class based on the field, and then instantiate the dynamically generated object class...

In the previous section, we generated a DataGrid that has not been formatted. This section uses the form layout to dynamically generate multiple binding columns and calculate the width of the Header of the binding column so that the binding column can properly occupy the entire DataGrid. In combination with the previous section, multiple DataGrid IDs are automatically generated based on the XML template to dynamically generate the DataGrid and layout.

This section first references two domain name spaces:

Using System. Windows. Data;
Using System. Text;

We paste the key code for generating the template column:

/// <Summary>
/// Create a DataGridTextColumn template Column
/// </Summary>
/// <Param name = "columnBindName"> Field name to be bound </param>
/// <Param name = "columnHeaderName"> Header of the template column </param>
/// <Param name = "width"> width of the template column </param>
/// <Returns> </returns>
Public maid (string columnBindName, string columnHeaderName, double width)
{
Maid ();
DgtextColumn. Binding = new Binding (columnBindName );
DgtextColumn. Header = columnHeaderName;
DgtextColumn. IsReadOnly = true;
DgtextColumn. Width = new DataGridLength (width );
Return dgtextColumn;
}

The preceding function creates a column of DataGridTextColumn and sets the fields, headers, read-only and width attributes it binds. Next, we will post a function that calculates the total number of bytes of a string (if the number of bytes occupies Chinese characters and the number of bytes occupies 1 English letter ):

/// <Summary>
/// String Length (in bytes)
/// </Summary>
/// <Param name = "str"> </param>
/// <Returns> </returns>
Static int StrLength (string str)
{
Int len = 0;
Byte [] B;

For (int I = 0; I <str. Length; I ++)
{
B = Encoding. UTF8.GetBytes (str. Substring (I, 1 ));
If (B. Length> 1)
Len + = 2;
Else
Len ++;
}

Return len;
}

The following source code starts to dynamically create a DataGrid and set the corresponding basic attributes. The width of the template column is calculated as follows:

1. the Header of the template can be Chinese characters or letters ). If the Chinese character occupies 2 bytes and the character occupies 1 byte, in the default DataGrid, we assume that each byte occupies 6 pixels on average, the length of the characters to be displayed is multiplied by 6 pixels, which is the length of the characters to be displayed. [StrLength (NameLenth) * 6]

2. The total width of the DataGrid must first be reduced by two pixels (because the left and right sides of the DataGrid are respectively 1), and then the total length of the display characters is subtracted, the remaining length is the allocable length. Dividing these lengths by the total number of fields is the pixel increment that each field can obtain. [Double Sub = dgrid. Width-StrLength (NameLenth) * 6-2;]

Third, in the foreach loop, multiply the number of bytes of each field by 6, plus the pixel increment of each field obtained in the second step, that is, the width of the current template column. [X + StrLength (gridClass. ShowName) * 6)]

// Dynamically generate a DataGrid and bind it to the data source
DataGrid dgrid = new DataGrid ();
Dgrid. HorizontalAlignment = HorizontalAlignment. Left;
Dgrid. verticalignment = verticalignment. Top;
Dgrid. AutoGenerateColumns = false;
Dgrid. Margin = new Thickness (20, 5, 0, 0 );
Dgrid. Width = 960;
Dgrid. Name = TableName;
// Calculate the total length of all Header characters in pixels, And then subtract the length from the DataGrid width. The result is divided by the total number of DataGrid columns, which is the increment of the number of columns that can be obtained in each column.
Double Sub = dgrid. Width-StrLength (NameLenth) * 6-2;
Double x = Sub/gridClassList. Count;
Foreach (GridClass gridClass in gridClassList)
{// Add template columns cyclically
Dgrid. Columns. Add (CreateDataGridTextColumn (gridClass. Name, gridClass. ShowName, x + StrLength (gridClass. ShowName) * 6 ));
}
Dgrid. ItemsSource = GetEnumerable (dicList). ToDataSource ();

At this point, we have generated an auto-assigned template column width to automatically generate the DataGrid instance based on XML. If you have any questions, please contact me.

The instance is written in VS2010 + Silverlight 4.0. To download the source code, click SLDanamicTextColumn.rar.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.