silverlight双向绑定 类绑定
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;
}
}
}
补充:软件开发 , C# ,