WPF 绑定以基础数据类型为集合的无字段名的数据源
WPF 绑定以基础数据类型为集合的无字段名的数据源
运行环境:Window7 64bit,.NetFramework4.61,C# 6.0; 编者:乌龙哈里 2017-02-21
我们在控件的数据绑定中经常是给定一个类,比如下面类似的:
Class Student
{
public int code;
public string name;
public int score;
}
然后用 List
但是,我们经常会碰到以基础数据类型,如 int 、string 之类为集合的无字段名的动态数据源,比如 List< int[ ] > 这样的,该如何绑定呢?
其实也简单,直接指定 T 的索引,{Binding [0]},{Binding [1]} 如此写。如下示列代码:
示例1(前端绑定):
前端 XAML 代码片段:
后端 C# 代码片段:
List<int[]> list = new List<int[]>();
int[] arr = new int[] { 1, 2, 3, 4 };
list.Add(arr);
arr = new int[] { 3, 4, 5, 6 };
list.Add(arr);
lsvList.ItemsSource = list;
运行结果如图:
示例2(后端用C#代码实现绑定):
前端XAML代码片段:
后端C#代码片段:
List<int[]> list = new List<int[]>();
int[] arr = new int[] { 1, 2, 3, 4 };
list.Add(arr);
arr = new int[] { 3, 4, 5, 6 };
list.Add(arr);
GridView gv = new GridView();
for (int i = 0; i < 4; i++)
{
GridViewColumn col = new GridViewColumn() { Header = headlist[i], DisplayMemberBinding = new Binding($"[{i}]") };
gv.Columns.Add(col);
}
lsvList.View = gv;
lsvList.ItemsSource = list;