OK,我們之前已經講過控件的綁定,那麼如果現在我定義一個user類,它有兩個屬性,分別是Name和Age,那麼如何前台的textbox綁定到這個類中的屬性呢?
下面我們講一種簡單的類綁定,首先我們聲明這個類:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace dataBind
{
public class user
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
int age;
public int Age
{
get { return age; }
set { age = value; }
}
}
}
現在我在前台界面托兩個textbox分別用來綁定類的Name和Age屬性,托一個按鈕用來顯示綁定的信息。界面設計如下:
由於textbox1和textbox2分別要綁定user類的Name和Age屬性,那麼我將他們兩個的文本值分別設置如下:
Text="{Binding Name,Mode=TwoWay}
Text="{Binding Age,Mode=TwoWay}
我們後台代碼寫成:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace dataBind
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
user u = new user();
private void buttonBind_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("名字:"+u.Name +"\n年齡"+ u.Age);
}
private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
u.Name = "安亭";
u.Age = 23;
textBox1.DataContext = u;
textBox2.DataContext = u;
}
}
}