学习silverlight基础之动态绑定非实体类
在上节中我们学会了数据绑定,但是如果我们不确定数据库中查询出来的表结构而且我也不想每次都这样创建实体类,该怎么办呢?
Silverlight中又不能使直接使用DataSet,但是我们可以用List<IDictionary<string, object>>来模拟一个数据表结构,在DBService中的代码如下:
1 [OperationContract]
2 public List<IDictionary<string, object>> ExecSqlQueryHash(string exSql)
3 {
4 string connectionString = WebConfigurationManager.AppSettings["DbServiceConnectionString"];
5 SqlConnection sqlConn = null;
6
7 if ((sqlConn != null) && (sqlConn.State != ConnectionState.Closed))
8 {
9 sqlConn.Open();
10 }
11 else
12 {
13 sqlConn = new SqlConnection(connectionString);
14 sqlConn.Open();
15 }
16 SqlDataAdapter data = new SqlDataAdapter(exSql, sqlConn);
17 DataSet ds = new DataSet();
18 data.Fill(ds, "djb");
19 List<IDictionary<string, object>> hashObjList = new List<IDictionary<string, object>>();
20 for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
21 {
22 Dictionary<string, object> hashObj = new Dictionary<string, object>();
23 for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
24 {
25 string colName = ds.Tables[0].Columns[j].ColumnName;
26 hashObj.Add(colName, ds.Tables[0].Rows[i][colName]);
27 }
28 hashObjList.Add(hashObj);
29 }
30 return hashObjList;
31 }
然后我们Silverlight该怎么接收并且在RadGridView中显示呢? 这里我们抄袭国外一哥们的解决方案,很强大...
利用IEnumerable<IDictionary>扩展一个ToDataSource的方法让Silverlight的数据感知控件的ItemsSource接收,看代码:
1 private void C_ExecSqlQueryHashCompleted(object sender, ExecSqlQueryHashCompletedEventArgs e)
2 {
3 RadGridView1.AutoGenerateColumns = false;
4 RadGridView1.Columns.Add(
5 new GridViewDataColumn
6 {
7 Header = "编号",
8 DataMemberBinding = new Binding("code")
9 });
10 RadGridView1.Columns.Add(
11 new GridViewDataColumn
12 {
13 Header = "日期",
14 DataMemberBinding = new Binding("date")
15 });
16 RadGridView1.Columns.Add(
17 new GridViewDataColumn
18 {
19 Header = "描述",
20 DataMemberBinding = new Binding("summery")
21 });
22 RadGridView1.ItemsSource = CalcEnumer(e).ToDataSource();
23
24 }
25
26
27 public IEnumerable<IDictionary> CalcEnumer(ExecSqlQueryHashCompletedEventArgs data)
28 {
29 for (int i = 0; i < data.Result.Count; i++)
30 {
31 var dict = new Dictionary<string, object>();
32 dict["code"] = data.Result[i]["code"];
33 dict["date"] = data.Result[i]["date"];
34 dict["summery"] = data.Result[i]["summery"];
35 yield return dict;
36 }
37 }
这里是扩展ToDataSource的代码,老外哪直接拷贝 - -
代码
1 namespace MySlPro
2 {
3 public static class DataSourceCreator
4 {
5 private static readonly Regex PropertNameRegex =
6 new Regex(@"^[A-Za-z]+[A-Za-z1-9_]*$", RegexOptions.Singleline);
7 public static object[] ToDataSource(this IEnumerable<IDictionary> list)
8 {
9 IDictionary firstDict = null;
10 bool hasData = false;
11 foreach (IDictionary currentDict in list)
12 {
13 hasData = true;
14 firstDict = currentDict;
15 break;
16 }
17 if (!hasData)
18 {
19 return new object[] { };
20 }
21 if (firstDict == null)
22 {
23 throw new ArgumentException("IDictionary entry cannot be null");
24 }
25 Type objectType = null;
26 TypeBuilder tb = GetTypeBuilder(list.GetHashCode());
27 ConstructorBuilder constructor =
28 tb.DefineDefaultConstructor(
29 MethodAttributes.Public |
30 MethodAttributes.SpecialName |
31 MethodAttributes.RTSpecialName);
32 foreach (DictionaryEntry pair in firstDict)
33 {
34 if (PropertNameRegex.IsMatch(Convert.ToString(pair.Key), 0))
35 {
36 CreateProperty(tb,
37 Convert.ToString(pair.Key),
38 pair.Value == null ?
39 typeof(object) :
40 pair.Value.GetType());
41 }
42 else
43 {
44 throw new ArgumentException(
45 @"Each key of IDictionary must be
46 alphanumeric and start with character.");
47 }
48 }
49 objectType = tb.CreateType();
50 return GenerateArray(objectType, list, firstDict);
51 }
52 private static object[] GenerateArray(Type objectType, IEnumerable<IDictionary> list, IDictionary firstDict)
53 {
54 var itemsSource = new List<object>();
55 foreach (var currentDict in list)
56 {
57 if (currentDict == null)
58 {
59 throw new ArgumentException("IDictionary entry cannot be null");
60 }
61 object row = Activator.CreateInstance(objectType);
62 foreach (DictionaryEntry pair in firstDict)
63 {
64 if (currentDict.Contains(pair.Key))
65 {
66 PropertyInfo property =
67 objectType.GetProperty(Convert.ToString(pair.Key));
68 property.SetValue(
69 row,
70 Convert.ChangeType(
71 currentDict[pair.Key],
72 property.PropertyType,
73 null),
74 null);
75 }
76 }
77 itemsSource.Add(row);
78 }
79 return itemsSource.ToArray();
80 }
81 private static TypeBuilder GetTypeBuilder(int code)
82 {
83 AssemblyName an = new AssemblyName("TempAssembly" + code);
84 AssemblyBuilder assemblyBuilder =
85 AppDomain.CurrentDomain.DefineDynamicAssembly(
86 an, AssemblyBuilderAccess.Run);
87 ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
88 TypeBuilder tb = moduleBuilder.DefineType("TempType" + code
89 , TypeAttributes.Public |
90 TypeAttributes.Class |
91 TypeAttributes.AutoClass |
92 TypeAttributes.AnsiClass |
93 TypeAttributes.BeforeFieldInit |
94 TypeAttributes.AutoLayout
95 , typeof(object));
96 return tb;
97 }
98 private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
99 {
100 FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName,
101 propertyType,
102 FieldAttributes.Private);
103
104 PropertyBuilder propertyBuilder =
105 tb.DefineProperty(
106 propertyName, PropertyAttributes.HasDefault, propertyType, null);
107 MethodBuilder getPropMthdBldr =
108 tb.DefineMethod("get_" + propertyName,
109 MethodAttributes.Public |
110 MethodAttributes.SpecialName |
111 MethodAttributes.HideBySig,
112 propertyType, Type.EmptyTypes);
113 ILGenerator getIL = getPropMthdBldr.GetILGenerator();
114 getIL.Emit(OpCodes.Ldarg_0);
115 getIL.Emit(OpCodes.Ldfld, fieldBuilder);
116 getIL.Emit(OpCodes.Ret);
117 MethodBuilder setPropMthdBldr =
118 tb.DefineMethod("set_" + propertyName,
119 MethodAttributes.Public |
120 MethodAttributes.SpecialName |
121 MethodAttributes.HideBySig,
122 null, new Type[] { propertyType });
123 ILGenerator setIL = setPropMthdBldr.GetILGenerator();
124 setIL.Emit(OpCodes.Ldarg_0);
125 setIL.Emit(OpCodes.Ldarg_1);
126 setIL.Emit(OpCodes.Stfld, fieldBuilder);
127 setIL.Emit(OpCodes.Ret);
128 propertyBuilder.SetGetMethod(getPropMthdBldr);
129 propertyBuilder.SetSetMethod(setPropMthdBldr);
130 }
131 }
132 }
调试运行:

阅读全文
类别:Silverlight 查看评论

浙公网安备 33010602011771号