Binding及与之配套的数据转换和校验是WPF的核心。一些详细的只是介绍,园子里到处都是,这里DebugLZQ不再赘述。
首先回顾下WPF常用的Binding数据源
1.控件属性---控件的属性与属性Binding
经典的例子如下:
<TextBox Height="23" HorizontalAlignment="Left" Margin="28,42,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Path=Value,ElementName=slider1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> <Slider Height="23" HorizontalAlignment="Left" Margin="28,94,0,0" Name="slider1" VerticalAlignment="Top" Width="225" />
重点是这里:
Text="{Binding Path=Value,ElementName=slider1,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
2.Object数据源
控件的属性与一个内存Object绑定,该对象所在类实现IPropertyChanged接口
using System.ComponentModel;// namespace Binding { class Machine:INotifyPropertyChanged { #region INotifyPropertyChanged 成员 public event PropertyChangedEventHandler PropertyChanged; #endregion private int temperature; public int Temperature { get { return temperature; } set { temperature = value; //引发事件 if (PropertyChanged != null) { PropertyChanged.Invoke(this, new PropertyChangedEventArgs("temperature")); } } } } }
页面布局如下:
using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace Binding { /// <summary> /// Window2.xaml 的交互逻辑 /// </summary> public partial class Window2 : Window { Machine machine; public Window2() { InitializeComponent(); //数据源 machine = new Machine(); //Binding System.Windows.Data.Binding binding = new System.Windows.Data.Binding(); binding.Source = machine; binding.Path = new PropertyPath("Temperature"); // BindingOperations.SetBinding(textBox1, TextBox.TextProperty, binding); } private void button1_Click(object sender, RoutedEventArgs e) { System.Timers.Timer timer = new System.Timers.Timer(); timer.Interval = 500; timer.Enabled = true; timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); } void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { machine.Temperature++; } } }
3.XML数据源
不去多说,前面的博文中有类似的
4.ADO.NET中的DataTable
即从数据库获得一个DataTable对象, Binding到DataGrid或ListView。
自定义数据库表定义如下:
//----------直接DataTable数据源------------------------------------- DataTable dataTable = SQLHelper.GetDataTable(); dataGrid1.ItemsSource = dataTable.DefaultView;
SQLHelper类如下,该静态类之定义了一个方法用来获得一个DataTable,下面的LINQ数据源使用相同的SQLHelper.GetDataTable()方法。
using System.Data.SqlClient; using System.Data; namespace Binding { class SQLHelper { public static string connstring = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\VS2010Pros\Binding\Binding\Database1.mdf;Integrated Security=True;User Instance=True"; public static DataTable GetDataTable() { using (SqlConnection conn = new SqlConnection(connstring)) { string sql = @"select Id,Name,Age from tb_Student"; SqlDataAdapter sda = new SqlDataAdapter(sql, conn); DataTable dt = new DataTable(); sda.Fill(dt); return dt; } } } }
在xaml中加入Binding,DataGrid控件定义如下:
<DataGrid AutoGenerateColumns="False" Height="130" HorizontalAlignment="Left" Margin="24,16,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="230" > <DataGrid.Columns> <DataGridTextColumn Header="Id" Width="60" Binding="{Binding Id}"/> <DataGridTextColumn Header="Name" Width="100" Binding="{Binding Name}"/> <DataGridTextColumn Header="Age" Width="60" Binding="{Binding Age}"/> </DataGrid.Columns> </DataGrid>
结果如下(因为DebugLZQ现在开启的是XP系统,所以界面有点丑):
5.LINQ 数据源 DataGrid ListView等控件Binding LINQ数据源
主要是LINQ to DataSet 和LINQ to SQL。
首先是LINQ to DataSet Binding到ListView。其中的dataTable获取方法和上面的一样。
//----------Linq to DataSet数据源---------------------------------------- var query = from row in dataTable.Rows.Cast<DataRow>() where Convert.ToString(row["Name"]).StartsWith("D") select new { Id=int.Parse(row["Id"].ToString()), Name=row["Name"].ToString(), Age = int.Parse(row["Age"].ToString()) }; listView1.ItemsSource = query;
ListView 定义及Binding如下:
<ListView Height="100" HorizontalAlignment="Left" Margin="24,173,0,0" Name="listView1" VerticalAlignment="Top" Width="224" > <ListView.View> <GridView> <GridViewColumn Header="Id" Width="60" DisplayMemberBinding="{Binding Id}"/> <GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding Name}"/> <GridViewColumn Header="Age" Width="60" DisplayMemberBinding="{Binding Age}"/> </GridView> </ListView.View> </ListView>
结果如下:
下面给是LINQ to SQL 数据源Binding到DataGrid控件。
用来映射tb_Student表的Student类定义如下:
using System.Data.Linq.Mapping; namespace Binding { [Table(Name="tb_Student")] class Student { [Column(IsPrimaryKey = true, DbType = "Int NOT NULL IDENTITY", IsDbGenerated = true, Name = "Id")] public int Id { get; set; } [Column(DbType = "nvarchar(20)", Name = "Name")] public string Name { get; set; } [Column(DbType = "int", Name = "Age")] public int Age { get; set; } } }
对数据源的LINQ操作如下,随便写了一个:
//---------Linq to SQL 数据源------------------------------------ System.Data.Linq.DataContext dc = new System.Data.Linq.DataContext(SQLHelper.connstring ); var students= dc.GetTable<Student>(); var query_2 = from s in students where s.Name.Contains("D") select s; dataGrid2.ItemsSource = query_2;
DataGrid 定义及Binding如下:
<DataGrid AlternatingRowBackground="#FFAACC0B" AutoGenerateColumns="False" Height="130" HorizontalAlignment="Left" Margin="267,74,0,0" Name="dataGrid2" VerticalAlignment="Top" Width="230"> <DataGrid.Columns> <DataGridTextColumn Binding="{Binding Id}" Header="Id" Width="60" /> <DataGridTextColumn Binding="{Binding Name}" Header="Name" Width="100" /> <DataGridTextColumn Binding="{Binding Age}" Header="Age" Width="60" /> </DataGrid.Columns> </DataGrid>
程序运行结果如下: