dt;
然后再构造函数中创建DataTable,赋予值并绑定即可
DataTable dt = CreateDt();
DataRow dr = dt.NewRow();
dr[0] = 1;
dr[1] = "狗娃";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 2;
dr[1] = "狗剩";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 1;
dr[1] = "铁蛋";
dt.Rows.Add(dr);
//将数据源设置为Dt的视图
this.listView1.ItemsSource = dt.DefaultView;
3.使用XML数据作为数据源
WPF提供了两套处理XML的类库:
1.符合DOM(Document Object Model 文档对象模式)标准类库:XmlDocument.XmlElement,XmlNode等类,这套类型特点中规中矩,功能强大,但也背负了太多的XML传统和复杂
2.以LINQ(Language-Intergrated Query 语言集成查询)为基础的类库,包括:XDocument,XElement,XNode,XAttribute等类,这套类库特点是可以通过LINQ进行查询和操作,方便快捷
首先使用第一种方案
先创建一个XML文件
<?xml version="1.0" encoding="utf-8" ?>
<StudentList>
<Student id="1">
<Name>狗娃</Name>
</Student>
<Student id="2">
<Name>狗剩</Name>
</Student>
<Student id="3">
<Name>铁蛋</Name>
</Student>
</StudentList>
然后创建XAML
<StackPanel Width="300" Name="stackPanel1">
<ListView Name="listView1">
<ListView.View>
<GridView>
<GridViewColumn Header="编号" DisplayMemberBinding="{Binding XPath=@id}">
</GridViewColumn>
<GridViewColumn Header="姓名" DisplayMemberBinding="{Binding XPath=Name}">
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
注意:XML绑定不是使用Path,而是XPath
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\资料\f盘\代码\c#\WPF\TreeView\TestSource\Students.xml");
//通过XmlDataProvider进行绑定数据
XmlDataProvider dp = new XmlDataProvider();
dp.Document = doc;
dp.XPath = @"StudentList/Student";
this.listView1.SetBinding(ListView.ItemsSourceProperty, new Binding() { Source=dp});
绑定XMl使用到了XmlDataProvider,这个类是将XMl做为数据源源的一种快捷方式.XmlDataPrivider有个Source属性,可以使用它直接指定XML文档地址(无论XML文档是存储在本地还是网络位置),所以也可以这么写
XmlDataProvider dp = new XmlDataProvider();
dp.Source = new Uri(@"C:\资料\f盘\代码\c#\WPF\TreeView\TestSource\Students.xml");
dp.XPath = @"StudentList/Student";
this.listView1.SetBinding(ListView.ItemsSourceProperty, new Binding() { Source=dp});
4.使用LINQ做为数据源
从3.0版本,.NET Framework开始支持LINQ,使用LINQ,可以方便的操作集合对象,LINQ查询结果是一个IEnumerable<T>类型对象,而IEnumerable<T>又派生自IEnumerable,所以可以作为列表控件的Items Source使用。
现在还还用刚开始创建的那个Student模型类和XAML代码,
public class Student
public int ID { get; set; }
public String Name { get; set; }
<StackPanel Height="300" Width="300" HorizontalAlignment="Left">
<ListView Name="listView1">
<ListView.View>
<GridView>
<GridViewColumn Header="编号" DisplayMemberBinding="{Binding ID}" Width="100"></GridViewColumn>
<GridViewColumn Header="姓名" DisplayMemberBinding="{Binding Name}" Width="100"></GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
我们只需更改数据源即可
List<Student> stus = new List<Student>()
new Student(){ID=1,Name="狗娃"},
new Student(){ID=2,Name="铁蛋"},
new Student(){ID=3,Name="狗剩"}
this.listView1.ItemsSource = from stu in stus where stu.Name.StartsWith("狗") select stu;
还可以将数据放在DataTable中
DataTable dt = CreateDt();
DataRow dr = dt.NewRow();
dr[0] = 1;
dr[1] = "狗娃";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 2;
dr[1] = "狗剩";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 1;
dr[1] = "铁蛋";
dt.Rows.Add(dr);
this.listView1.ItemsSource = from row in dt.Rows.Cast<DataRow>()
where (row["Name"] as String).StartsWith("狗")
select new Student
ID = Convert.ToInt32(row["ID"]),
Name = row["Name"] as String
又或者使用XML
XDocument xd = XDocument.Load(@"C:\资料\f盘\代码\c#\WPF\TreeView\TestSource\Students.xml");
this.listView1.ItemsSource = from ele in xd.Descendants("Student")
where (ele.Elements().First()).Value.StartsWith("狗")
select new Student
ID = Convert.ToInt32(ele.Attribute("id").Value),
Name = ele.Elements().First().Value
5.ObjectDataProvider做为数据源
理想情况下,上游程序员将类设计好,使用属性把数据暴露出来,下游程序员将这些类作为Binding的Source,把属性做为Binding的Path来消费。但很难保证一个类的属性都暴露出来,例如需要的数据可能是方法的返回值。而重新设计底层类的风险会比较高,况且有可能引用的类库情况我们不可能更改已经便宜好的类,这时候就需要使用ObjectDataProvider来包装做为Binding源的数据对象。
ObjectDataProvider顾名思义就是把对对象做为数据源提供给Binding。上面使用的XmlDataProvider,这两个类的父类都是DataSourceProvider抽象类。
现在做一个这样例子。
有一个Calculator类,它具有一个加法方法
class Caculate
public string Add(string arg1, string arg2)
double x = 0;
double y = 0;
double z = 0;
if (double.TryParse(arg1, out x) && double.TryParse(arg2, out y))
z = x + y;
return z.ToString();
return "Iput Error";
然后在XAML中创建三个TextBox框
<StackPanel Height="300" Width="300" HorizontalAlignment="Left">
<TextBox Name="txtBox1" Width="120" HorizontalAlignment="Left"></TextBox>
<TextBox Name="txtBox2" Width="120" Margin="0 10" HorizontalAlignment="Left"></TextBox>
<TextBox Name="txtBox3" Width="120" Margin="0 10" HorizontalAlignment="Left"></TextBox>
</StackPanel>
要实现的需求就是通过Caculate方法实现第三个文本框是前两个之和,也就是我们需要将前两个文本框绑定到Add方法的两个参数,第三个绑定到返回值上。
然后我们在构造函数中编写后台代码
ObjectDataProvider odp = new ObjectDataProvider();
//设置用于绑定源的对象
odp.ObjectInstance = new Caculate();
//设置调用方法的名称
odp.MethodName = "Add";
//添加方法参数
odp.MethodParameters.Add("0");
odp.MethodParameters.Add("0");
//绑定参数到txtBox1和txtBox2
this.txtBox1.SetBinding(TextBox.TextProperty, new Binding("MethodParameters[0]") { Source = odp, BindsDirectlyToSource = true, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
this.txtBox2.SetBinding(TextBox.TextProperty, new Binding("MethodParameters[1]") { Source = odp, BindsDirectlyToSource = true, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged });
//绑定结果
this.txtBox3.SetBinding(TextBox.TextProperty, new Binding(".") { Source = odp});
先来分析一下上面代码。ObjectDataProvider类的作用是包装一个以方法暴露数据的对象,这里就先创建一个ObjectDataProvider的对象.然后用一个Caculate对象做为ObjectInstance对象复制。这就是把Caculate对象包装在了ObjectDataProvider里面。接着使用MethodName属性指定调用的Caculate对象中Add的方法。问题来了,如果Caculator有多个构造器参数的方法Add应该如何区分?我们知道,重载方法的区别在于参数列表,紧接着两句就是向MethodParameter属性里面加入两个string类型的参数,这就相当于告诉ObjectDataProvider对象去调用Caculator对象中具有两个string类型参数的Add方法,换句话说,MethodParameter对于参数的感应是非常敏感的。
准备好数据源之后,我们准备创建Binding。前面我们已经讲过使用索引器作为Binding的Path,第一个Binding它的Source是一个ObjectDataProvider对象,Path是ObjectDataProvider中MethodParameters所引用的第一个元素。BindsDirectlyToSource这句话是告诉Binding只是将UI上的值传递给源而不是被ObjectDataProvider包装的Caculator,同时UpdateSourceTrigger设置为UI只要一有变化就更新Source。第二个Binding只是对第一个的翻版,只是把Path属性指向了第二个元素。第三个binding仍然使用ObjectDataProvider作为Source,但使用“.”作为Path----前面讲过,当数据源本身就是数据的时候就用“.”来做为Path,在XAML中"."可以不写。
注意: 在ObjectDataProvider对象作为Binding的Source的时候,这个对象本身就代表了数据,所以这里的Path使用的“.”,而不是Data属性。
6.使用RelativeSource当绑定源
当一个Binding有明确的来源的时候,我们可以通过Source或者ElementName赋值的办法让Binding与之关联。有些时候我们不能确定作为Source对象叫什么名字,但是我们知道它与做为Binding目标对象在UI上的相对关系,比如控件自己关联自己的某个数据,关联自己某级容器的数据,这时候就需要用到Binding的RelativeSource属性。
RelativeSource属性的类型是RelativeSource类,通过这个类的几个静态或者非静态的属性我们可以控制它搜索相对数据源的方式。
<StackPanel x:Name="stackPanel1" Margin="10">
<StackPanel x:Name="stackPanel2" Margin="10">
<Grid Name="grid2">
<TextBox Name="txtBox1" Width="100" Height="23" HorizontalAlignment="Left"></TextBox>
</Grid>
</StackPanel>
</StackPanel>
我们看下上面结构 这个XAML结构为 StackPanel1----StackPanel2---Grid2---TextBox 。然后以相对路径来为TextBox进行绑定
RelativeSource relative = new RelativeSource(RelativeSourceMode.FindAncestor);
//设置要查找的上级级别
relative.AncestorLevel = 1;
//设置要查找的类型
relative.AncestorType = typeof(StackPanel);
Binding binding = new Binding("Name")
{//设置相对绑定的数据源
RelativeSource = relative
this.txtBox1.SetBinding(TextBox.TextProperty, binding);
然后再观察以上代码。相对绑定源类为RelativeSource类,这个类构造可以放一个RelativeSourceMode枚举,这个枚举描述与绑定目标的位置相对的绑定源位置。枚举值有四个
PreviousData:当前显示向列表的上一个数据项
TemplateParent:引用应用了模板的元素,其中此模板中存在数据绑定元素。
Self:引用正在绑定的元素,允许你该元素的一个属性绑定到同一元素的其他属性上。
FindAncestor:引用数据绑定元素的父链中的上级。 可用于绑定到特定类型的上级或其子类
在这里设置为了FindAncestor. 然后为RelativeSource设置查找的级别和查找的类型。这里是先筛选类型,再筛选级别,比如现在查找的是深度为1的StackPanel。所以选中的是StackPanel2 而不是Grid2 。最后将RelativeSource对象设置为Binding的数据源
注意:设置数据源使用的是RelativeSource而不是Source
原文:WPF QuickStart系列之数据绑定(Data Binding)
这篇博客将展示WPF DataBinding的内容。
首先看一下WPF Data Binding的概览,
Binding Source可以是任意的CLR对象,或者XML文件等,Binding Target需要有依赖属性。
Mapping URI的格式是
clr-namespace:[;assembly=]
(1)如果自定义类和XAML处在同一个Assembly之中,只还需要提供clr-namespace值。
Binding作为数据的桥梁,连通业务逻辑层的对象(源对象)和UI的控件对象(目标对象)。在这座桥梁上,我们不仅可以控制在源对象与目标对象是双向通行还是单向通行。还可以控制数据的放行时机,甚至可以在这座桥上搭建一些关卡用来转换数据类型或者检验数据的正确性
我们先做一个最基本的例子,