适用于silverlight3、4、5
1. 新建一个项目,在MainPage.Xaml文件中添加控件,代码如下:
View Code
2. 新建一个类Myself.cs作为数据源
View Code
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 SilverlightApplication_DynamicBindings{public class MySelf{public string MyName { get; set; }public int MyAge { get; set; }public string MySex { get; set; }}}
3. 在MainPage.Xaml.cs 文件中,实例化类,并进行数据绑定
View Code
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 SilverlightApplication_DynamicBindings{public partial class MainPage : UserControl{public MainPage(){InitializeComponent();//初始化Myself实例MySelf i = new MySelf();MyName = "小刀";MyAge = 24;MySex = "男";//在C#代码中创建绑定this.MyName.SetBinding(TextBlock.TextProperty, new System.Windows.Data.Binding("MyName"));this.MyAge.SetBinding(TextBlock.TextProperty, new System.Windows.Data.Binding("MyAge"));this.MySex.SetBinding(TextBlock.TextProperty, new System.Windows.Data.Binding("MySex"));//将Grid的上下文设置问Myself实例GridMyself.DataContext = i;}}}
运行效果如下:
总结:在这个例子中,textblock控件的Text属性是在C#代码中绑定的,实在程序运行过程中动态绑定的。