本文主要针对使用DataGrid动态绑定数据对象,并实现行列转换效果。

一,前台绑定

<sdk:DataGrid x:Name="dataGrid2" Style="{StaticResource ResourceKey=safeDataGrid2}" />
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Test.Util; namespace Test
{
public partial class MainPage : UserControl
{
public Md Model = null;
private DispatcherTimer timer;
int index = 0;
/// <summary>
///
/// </summary>
public ObservableCollection<Obj> objs = new ObservableCollection<Obj>(); public MainPage()
{
InitializeComponent();
init();
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 8);
timer.Tick += timer_Tick;
timer.Start();
} /// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void timer_Tick(object sender, EventArgs e)
{
var ramd = new Random();
foreach (var tag in Model.Tags)
{
foreach (var para in Consts.Params)
{
var rv = index % 2 == 0 ? ramd.Next(2, 10) : ramd.Next(1, 5);
var o = new Obj
{
IsAlarm = false,
Value = (0.5 + rv).ToString(),
State = index % 2 == 0 ? 1 : 0,
MeterId = tag.F_METER_ID,
MeterName = tag.F_METER_NAME,
ParaId = para.Id
};
if (para.Id == "10")
{
o.IsAlarm = false;
o.ParaId = string.Empty;
o.State = 0;
o.Value = string.Empty;
}
var temp = objs.FirstOrDefault(i => i.MeterName.Equals(o.MeterName) && i.ParaId == o.ParaId);
if (temp != null)
{
temp.IsAlarm = o.IsAlarm;
temp.State = o.State;
temp.Value = o.Value;
}
else
objs.Add(o);
}
}
//CommHelper.GetSource(Model.Tags, objs, ref this.dataGrid2);
CommHelper.BindData(Model.Tags, objs, ref this.dataGrid2);
index++;
} /// <summary>
///
/// </summary>
void init()
{
Model = new Md();
Model.Tags = new List<T_METER>();
Model.Eles = new List<Param>();
for (int i = 0; i < 1; i++)
{
var temp = new T_METER
{
F_BUILD_ID = "440300B059",
F_METER_ID = string.Format("TAG_{0}", i),
F_METER_NAME = string.Format("CM-{0}", i)
};
if (i == 0)
temp.F_EQT_TYPE = "D";
else if (i == 1)
temp.F_EQT_TYPE = "C";
else if (i == 2)
temp.F_EQT_TYPE = "E";
else
temp.F_EQT_TYPE = "A";
Model.Tags.Add(temp);
}
this.dataGrid1.ItemsSource = Consts.Params;
CommHelper.CreateDataGrid(Model.Tags, ref this.dataGrid2);
}
} /// <summary>
///
/// </summary>
public class Md
{
/// <summary>
/// 参数集合
/// </summary>
public List<Param> Eles { get; set; }
/// <summary>
/// 电表集合
/// </summary>
public List<T_METER> Tags { get; set; }
}
/// <summary>
///
/// </summary>
public class T_METER
{
public string F_BUILD_ID { get; set; }
public string F_METER_ID { get; set; } public string F_METER_NAME { get; set; } public string F_EQT_TYPE { get; set; } public string F_VALUE { get; set; }
} /// <summary>
/// 参数
/// </summary>
public class Param
{
public string Id { get; set; } public string Name { get; set; }
} /// <summary>
/// 绑定数据对象
/// </summary>
public class Obj
{
/// <summary>
/// 对应参数编号
/// </summary>
public string ParaId { get; set; } public string MeterId { get; set; }
/// <summary>
/// 电表名称
/// </summary>
public string MeterName { get; set; }
/// <summary>
/// 开关状态0-关,1-开
/// </summary>
public int State { get; set; }
/// <summary>
/// OPC读取值
/// </summary>
public string Value { get; set; }
/// <summary>
/// 是否报警
/// </summary>
public bool IsAlarm { get; set; } } }

  

二,动态列对象

 using System.Collections.Generic;

 namespace Test.Util
{
/* ==============================
* Desc:DynamicColumn
* Author:hezp
* Date:2014/8/14 15:49:17
* ==============================*/
public class DynamicColumn
{
/// <summary>
/// 列名
/// </summary>
public string ColumnName { get; set; }
/// <summary>
/// 列对应集合
/// </summary>
public List<string> Values { get; set; }
}
}

三,DataGrid动态生成类

 using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel; namespace Test.Util
{
/* ==============================
* Desc:CommHelper
* Author:hezp
* Date:2014/8/14 15:58:26
* ==============================*/
public class CommHelper
{
/// <summary>
///
/// </summary>
/// <param name="columnBindName"></param>
/// <param name="columnHeaderName"></param>
/// <param name="width"></param>
/// <param name="index"></param>
/// <returns></returns>
private static DataGridTemplateColumn CreateDataGridTextColumn(string columnBindName, string columnHeaderName, T_METER tag)
{
DataGridTemplateColumn dgColumn = new DataGridTemplateColumn();
dgColumn.Header = columnHeaderName;
dgColumn.IsReadOnly = true;
var w = ;
if (tag != null)
{
if (tag.F_EQT_TYPE.Equals("D"))
{
dgColumn.HeaderStyle = ResourcesWrapper.GetStyle<Style>("safeByqStyle");
w = ;
}
else if (tag.F_EQT_TYPE.Equals("B"))
{
dgColumn.HeaderStyle = ResourcesWrapper.GetStyle<Style>("safeSingleDrStyle");
w = ;
}
else if (tag.F_EQT_TYPE.Equals("C"))
{
dgColumn.HeaderStyle = ResourcesWrapper.GetStyle<Style>("safeDoubleDrStyle");
w = ;
}
else if (tag.F_EQT_TYPE.Equals("E"))
{
dgColumn.HeaderStyle = ResourcesWrapper.GetStyle<Style>("safeHookStyle");
w = ;
}
else
dgColumn.HeaderStyle = ResourcesWrapper.GetStyle<Style>("safeMeterStyle");
}
else
dgColumn.HeaderStyle = ResourcesWrapper.GetStyle<Style>("safeMeterStyle"); dgColumn.CellStyle = ResourcesWrapper.GetStyle<Style>("safeCellStyle"); StringBuilder cellTemplate = new StringBuilder();
cellTemplate.Append("<DataTemplate ");
cellTemplate.Append(" xmlns='http://schemas.microsoft.com/client/2007' ");
cellTemplate.Append(" xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
cellTemplate.Append(" xmlns:c='clr-namespace:Test.Controls;assembly=Test.Controls' ");
cellTemplate.Append(" xmlns:local = 'Test");
cellTemplate.Append(";assembly=Test'>");
cellTemplate.Append(string.Format("<c:CustomCell Width='{1}' Text='{{Binding {0}}}'/>", columnBindName, w));
cellTemplate.Append("</DataTemplate>");
dgColumn.CellTemplate = (DataTemplate)XamlReader.Load(cellTemplate.ToString());
dgColumn.CellTemplate.LoadContent(); return dgColumn;
} /// <summary>
///
/// </summary>
/// <param name="SourceList"></param>
/// <returns></returns>
private static IEnumerable<IDictionary> GetEnumerable(List<Dictionary<string, string>> SourceList)
{
for (int i = ; i < SourceList.Count; i++)
{
var dict = new Dictionary<string, string>();
dict = SourceList[i];
yield return dict;
}
}
/// <summary>
///
/// </summary>
/// <param name="list"></param>
/// <param name="objs"></param>
/// <returns></returns>
private static List<DynamicColumn> Grenartor(List<T_METER> list, ObservableCollection<Obj> objs)
{
var columns = new List<DynamicColumn>();
if (null == list) return null;
var ms = from p in list
group p by new { p.F_BUILD_ID, p.F_METER_ID, p.F_METER_NAME } into gg
select gg.Key;
var ramd = new System.Random();
foreach (var m in ms)
{
var column = new DynamicColumn
{
ColumnName = string.Format("{0}____{1}", m.F_METER_NAME, )//格式:支路名称|开关状态值
};
if (objs != null)
{
var obj = objs.FirstOrDefault(i => i.MeterName.Equals(m.F_METER_NAME));
if (obj != null)
column.ColumnName = string.Format("{0}____{1}", obj.MeterName, obj.State);
}
column.Values = new List<string>();
var count = Consts.Params.Count;
for (int i = ; i < count; i++)
{
var v = false;//是否显示按钮
if (i == count - )
v = true;
if (objs != null)
{
var temp = objs.FirstOrDefault(j => j.MeterName.Equals(m.F_METER_NAME) && !string.IsNullOrEmpty(j.ParaId) && j.ParaId.Equals(Consts.Params[i].Id));
if (temp != null)
column.Values.Add(string.Format("{0}____{1}____{2}____{3}____{4}____{5}____{6}", m.F_BUILD_ID, m.F_METER_ID, m.F_METER_NAME, temp.Value, v, temp.IsAlarm, Consts.Params[i].Id));
else
column.Values.Add(string.Format("{0}____{1}____{2}____{3}____{4}____{5}____{6}", m.F_BUILD_ID, m.F_METER_ID, m.F_METER_NAME, "-", v, false, Consts.Params[i].Id));//格式:建筑编号____支路编号____支路名称____数值____是否是按钮____是否报警
}
else
column.Values.Add(string.Format("{0}____{1}____{2}____{3}____{4}____{5}____{6}", m.F_BUILD_ID, m.F_METER_ID, m.F_METER_NAME, "-", v, false, Consts.Params[i].Id));
}
columns.Add(column);
}
return columns;
}
/// <summary>
/// 绑定数据
/// </summary>
/// <param name="tags"></param>
/// <param name="objs"></param>
/// <param name="datagrid"></param>
public static void BindData(List<T_METER> tags, ObservableCollection<Obj> objs, ref DataGrid datagrid)
{
var list = Grenartor(tags, objs);
var dataSources = new List<Dictionary<string, string>>();
for (int j = ; j < ; j++)
{
var dict = new Dictionary<string, string>();//数据行(Key:列名,Value:列值)
list.ForEach(item =>
{
dict.Add(item.ColumnName.Replace(" ", "_").Replace("-", "_"), item.Values[j]);
});
dataSources.Add(dict);
}
foreach (var item in list)
{
var index = list.IndexOf(item);
var arr = Regex.Split(item.ColumnName, "____", RegexOptions.IgnoreCase);
var tag = tags.FirstOrDefault(i => i.F_METER_NAME.ToUpper().Equals(arr[].ToUpper()));
var column = CreateDataGridTextColumn(item.ColumnName.Replace(" ", "_").Replace("-", "_"), item.ColumnName, tag);
var cl = datagrid.Columns.FirstOrDefault(i => i.Header.ToString().StartsWith(tag.F_METER_NAME));
if (cl != null)
cl = column;
else
datagrid.Columns.Add(column);
}
datagrid.ItemsSource = GetEnumerable(dataSources).ToDataSource();
} public static void GetSource(List<T_METER> tags, ObservableCollection<Obj> objs, ref DataGrid datagrid)
{
var list = Grenartor(tags, objs);
var dataSources = new List<Dictionary<string, string>>();
for (int j = ; j < ; j++)
{
var dict = new Dictionary<string, string>();//数据行(Key:列名,Value:列值)
list.ForEach(item =>
{
dict.Add(item.ColumnName.Replace(" ", "_").Replace("-", "_"), item.Values[j]);
});
dataSources.Add(dict);
}
datagrid.ItemsSource = GetEnumerable(dataSources).ToDataSource();
} public static void CreateDataGrid(List<T_METER> tags, ref DataGrid datagrid)
{
var list = Grenartor(tags, null);
var dataSources = new List<Dictionary<string, string>>();
for (int j = ; j < ; j++)
{
var dict = new Dictionary<string, string>();//数据行(Key:列名,Value:列值)
list.ForEach(item =>
{
dict.Add(item.ColumnName.Replace(" ", "_").Replace("-", "_"), item.Values[j]);
});
dataSources.Add(dict);
}
foreach (var item in list)
{
var index = list.IndexOf(item);
var arr = Regex.Split(item.ColumnName, "____", RegexOptions.IgnoreCase);
var tag = tags.FirstOrDefault(i => i.F_METER_ID.ToUpper().Equals(arr[].ToUpper()));
var column = CreateDataGridTextColumn(item.ColumnName.Replace(" ", "_").Replace("-", "_"), item.ColumnName, tag);
var cl = datagrid.Columns.FirstOrDefault(i => i.Header.ToString().StartsWith(tag.F_METER_NAME));
if (cl != null)
cl = column;
else
datagrid.Columns.Add(column);
}
datagrid.ItemsSource = GetEnumerable(dataSources).ToDataSource();
}
}
}

四,数据源构造(实现行列转换)类

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Reflection.Emit; namespace Test.Util
{
/* ==============================
* Desc:DataSourceCreator
* Author:hezp
* Date:2014/8/14 15:51:04
* ==============================*/
public static class DataSourceCreator
{
public static ObservableCollection<object> ToDataSource(this IEnumerable<IDictionary> list)
{
IDictionary firstDict = null;
bool hasData = false;
foreach (IDictionary currentDict in list)
{
hasData = true;
firstDict = currentDict;
break;
}
if (!hasData)
{
return new ObservableCollection<object> { };
}
if (firstDict == null)
{
throw new ArgumentException("IDictionary entry cannot be null");
}
Type objectType = null;
TypeBuilder tb = GetTypeBuilder(list.GetHashCode());
ConstructorBuilder constructor =
tb.DefineDefaultConstructor(
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.RTSpecialName);
foreach (DictionaryEntry pair in firstDict)
{ CreateProperty(tb,
Convert.ToString(pair.Key),
pair.Value == null ?
typeof(object) :
pair.Value.GetType()); }
objectType = tb.CreateType();
return GenerateArray(objectType, list, firstDict);
}
private static ObservableCollection<object> GenerateArray(Type objectType, IEnumerable<IDictionary> list, IDictionary firstDict)
{
var itemsSource = new ObservableCollection<object>();
foreach (var currentDict in list)
{
object row = Activator.CreateInstance(objectType);
foreach (DictionaryEntry pair in firstDict)
{
if (currentDict.Contains(pair.Key))
{
PropertyInfo property =
objectType.GetProperty(Convert.ToString(pair.Key));
property.SetValue(
row,
Convert.ChangeType(
currentDict[pair.Key],
property.PropertyType,
null),
null);
}
}
itemsSource.Add(row);
}
return itemsSource;
}
private static TypeBuilder GetTypeBuilder(int code)
{
AssemblyName an = new AssemblyName("TempAssembly" + code);
AssemblyBuilder assemblyBuilder =
AppDomain.CurrentDomain.DefineDynamicAssembly(
an, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
TypeBuilder tb = moduleBuilder.DefineType("TempType" + code
, TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout
, typeof(object));
return tb;
}
private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
{
FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName,
propertyType,
FieldAttributes.Private); PropertyBuilder propertyBuilder =
tb.DefineProperty(
propertyName, PropertyAttributes.HasDefault, propertyType, null);
MethodBuilder getPropMthdBldr =
tb.DefineMethod("get_" + propertyName,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig,
propertyType, Type.EmptyTypes);
ILGenerator getIL = getPropMthdBldr.GetILGenerator();
getIL.Emit(OpCodes.Ldarg_0);
getIL.Emit(OpCodes.Ldfld, fieldBuilder);
getIL.Emit(OpCodes.Ret);
MethodBuilder setPropMthdBldr =
tb.DefineMethod("set_" + propertyName,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig,
null, new Type[] { propertyType });
ILGenerator setIL = setPropMthdBldr.GetILGenerator();
setIL.Emit(OpCodes.Ldarg_0);
setIL.Emit(OpCodes.Ldarg_1);
setIL.Emit(OpCodes.Stfld, fieldBuilder);
setIL.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getPropMthdBldr);
propertyBuilder.SetSetMethod(setPropMthdBldr);
}
}
}

五,显示效果

Silverlight日记:动态生成DataGrid、行列装换、动态加载控件的更多相关文章

  1. 解决tableView中cell动态加载控件的重用问题

    解决tableView中cell动态加载控件的重用问题 tableView的cell,有时候需要在运行时取得对应的数据后才能够动态的创建该cell中的控件并加载到该cell中,此时,你一定会遇到重用问 ...

  2. uGUI动态加载控件位置错误

    最近在使用uGUI时遇到了一个问题,在此记录一下.在Canvas的Render Mode设置为Screen Space-Overlay模式时,动态加载控件是不会发生问题的.但是在Screen Spac ...

  3. uGUI动态加载控件位置错误(转自:https://www.cnblogs.com/mezero/p/4542939.html)

    最近在使用uGUI时遇到了一个问题,在此记录一下.在Canvas的Render Mode设置为Screen Space-Overlay模式时,动态加载控件是不会发生问题的.但是在Screen Spac ...

  4. js动态加载控件jsp页面

    例子1:(具体参照drp中的flow_card_add.jsp)<script>    var rowIndex = 0;     function addOneLineOnClick() ...

  5. Android 动态背景的实现以及SurfaceView中添加EditText控件

    首先还是一贯作风,我们先看案例: \ 静态图看不出来效果,如果用过此软件(扎客)的同学们都知道,她的背景会动.怎么样,是不是觉得很时尚,起码比静态的要好(个人观点).其实实现起来并不复杂,这个如果让做 ...

  6. PHP+Mysql+easyui点击左侧tree菜单对应表名右侧动态生成datagrid加载表单数据(二)

    关于tree菜单生成,参考我的另一篇博文地址tree 菜单 实现功能:点击左侧tree菜单中的table,右侧通过datagrid加载出该表对用的所有数据 难点:获取该表的所有列名,动态生成datag ...

  7. Adroid动态加载Apk-插件化技术框架(动态代理方案)

    技术:Android + java +动态加载+插件化   概述 为什么要使用插件化?在开发中,一个项目只会越做越大.初始版本可能是单一功能,后续可能加上各种风马牛不相及的功能.所以我认为插件化可以使 ...

  8. 180807-Quick-Task 动态脚本支持框架之Groovy脚本加载执行

    Quick-Task 动态脚本支持框架之Groovy脚本加载执行 上一篇简答说了如何判断有任务动态添加.删除或更新,归于一点就是监听文件的变化,判断目录下的Groovy文件是否有新增删除和改变,从而判 ...

  9. WPF 动态生成DataGrid及动态绑定解决方案

    一.场景 有过WPF项目经验的朋友可能都知道,如果一个DataGrid要绑定静态的数据是非常的简单的(所谓静态是指绑定的数据源的类型是静态的),如下图所示,想要显示产品数据,只需绑定到一个产品列表即可 ...

随机推荐

  1. Pycharm 设置TextStyle

    之前在脚本中选择了一个字符串, PyCharm会"高亮"所有相同的字符串, 但是我不满意这个"高亮"的颜色,因为和背景色太相似了,所以需要做一下操作,修改这个& ...

  2. 51nod1109(bfs)

    题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1109 题意:中文题诶- 思路:可以用二叉树构建,根节点为 1, ...

  3. 查看java版本

    我们可以使用 -version 参数来查看当前 Java 的运行版本,命令如下:java -version 以上代码实例输出结果为: java version “1.6.0_13”Java(TM) S ...

  4. 页面出现滚动条时,body里面的内容不能自动居中?

    弹窗后允许页面滚动 这种方式通常使用 position: absolute; ,可以看看我做的这个 Demo.主要用来应对弹窗内容很大很多的情况,超过了屏幕的宽高需要产生滚动条来方便浏览者查看.有一些 ...

  5. HDU-2586-How far away(LCA Tarjan离线算法)

    链接:https://vjudge.net/problem/HDU-2586 题意: 勇气小镇是一个有着n个房屋的小镇,为什么把它叫做勇气小镇呢,这个故事就要从勇气小镇成立的那天说起了,修建小镇的时候 ...

  6. hdu2027 trie树 字典树模板

    #include <iostream> #include <cstdio> #include <cstring> #include <sstream> ...

  7. 如何使用在Windows 下AspNetCore Api 和 consul

    在Windows 下如何使用 AspNetCore Api 和 consul https://blog.csdn.net/sD7O95O/article/details/80750803 一.概念:什 ...

  8. Announcing .NET Core 2.1

    Announcing .NET Core 2.1 https://blogs.msdn.microsoft.com/dotnet/2018/05/30/announcing-net-core-2-1/ ...

  9. JavaSE---基本网络支持

    1.Java为网络支持提供了java.net包,该包下的URL和URLConnection等类提供了 以编程方式访问WEB服务 的功能: 2.URLDecoder.URLEncoder提供了 普通字符 ...

  10. LWIP学习之流程架构

    一 STM32F107的网络接口配置:#include "stm32_eth.h" 1.1 打开网口时钟,响应IO配置.NVIC中断:通过调用Ethernet_Configurat ...