private GridView BindHeader(DataTable dtSource)
{
GridView gv = new GridView();
foreach (DataColumn item in dtSource.Columns)
{
GridViewColumn gvc = new GridViewColumn();
gvc.Header = item.ColumnName;
//这里面的tmpRight是一个使用;号隔开的字符串变量,被隔开的字符串表示不要靠右显示的列。
//如果item.ColumnName在这个字符串变量里面不存在则靠右显示。
if (tmpRight.IndexOf(item.ColumnName.Trim()) == -1)
{
DataTemplate dt = new DataTemplate();
FrameworkElementFactory fef = new FrameworkElementFactory(typeof(TextBlock));
Binding b = new Binding(item.ColumnName);
fef.SetBinding(TextBlock.TextProperty, b);
fef.SetValue(TextBlock.TextAlignmentProperty, TextAlignment.Right);
fef.SetValue(TextBlock.PaddingProperty, new Thickness(0, 0, 15, 0));
fef.SetBinding(TextBlock.WidthProperty, new Binding("ActualWidth") { Source = gvc });
dt.VisualTree = fef;
gvc.CellTemplate = dt;
}
else
{
Binding binding = new Binding(item.ColumnName);
DataTemplate tmplate = new DataTemplate();
gvc.DisplayMemberBinding = binding;
}
gvc.Width = item.ColumnName == "序号" ? 50 : GetStrLen(item.ColumnName);
gv.Columns.Add(gvc);
}
return gv;
}
dtSource为要显示的列的数据源,因为这里是动态添加要显示的列的。