WPF 动态创建 DataTemplate 及数据绑定
运行环境:Window7 64bit,.NetFramework4.61,C# 6.0; 编者:乌龙哈里 2017-02-22
参考:
正文:
方法就是在内存中动态生成一个 XAML ,仿照前端一样写一个 DataTemplate 。如下面的前端:
<Window.Resources>
<DataTemplate x:Key="123">
<TextBox Text="{Binding [3]}"/>
</DataTemplate>
</Window.Resources>
下面开始模拟它写,注意:
XNamspace、XElement 都要 using System.Xml.Linq;
XmlReader 要 using System.Xml;
XamlReader 要 using System.Windows.Markup;
示例1:
List<int[]> list = new List<int[]>();
list.Add(new int[] {1,2,3,4 });
list.Add(new int[] { 3,4,5,6 });
list.Add(new int[] { 4, 5, 6, 7 });
list.Add(new int[] { 10,12, 13, 14 });
GridView view = new GridView();
view.Columns.Add(new GridViewColumn { Header="A",DisplayMemberBinding=new Binding("[0]")});
view.Columns.Add(new GridViewColumn { Header = "B",DisplayMemberBinding=new Binding("[1]")});
view.Columns.Add(new GridViewColumn { Header = "C", DisplayMemberBinding = new Binding("[2]") });
XNamespace ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
XElement xe =new XElement(ns +"DataTemplate",
new XAttribute("xmlns", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"),
new XElement(ns +"TextBox", new XAttribute("Text", @"{Binding [3]}"))
);
XmlReader xr = xe.CreateReader();
DataTemplate dt = XamlReader.Load(xr) as DataTemplate;
view.Columns.Add(new GridViewColumn { Header = "D", CellTemplate = dt });
//lsvShow 是个 ListView 控件
lsvShow.View = view;
lsvShow.ItemsSource = list;
运行结果如下图: