Xaml代码
<!-- 简单对象的绑定 -->
<StackPanel Name="stackPanel" HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Vertical">
<TextBox Name="lbId" Text="{Binding ID}"/> //使用Binding绑定ID属性
<TextBox Name="lbName" Text="{Binding Name}"/> //使用Binding绑定Name属性
<TextBox Name="lbAge" Text="{Binding Age}"/> //使用Binding绑定Age属性
</StackPanel>
C#代码
public MainWindow()
{
InitializeComponent();
Init();
}
StudentData stuData = new StudentData(); //实例类
public void Init()
{
stuData.ID = 1001;
stuData.Name = "小明";
stuData.Age = 18;
stuData.Name = "小明";
//this.DataContext = stuData; //整个窗口内的所有元素都可以绑定此数据
stackPanel.DataContext = stuData; //仅stackPanel内的所有元素可以绑定此数据
}
//声明类
public class StudentData
{
public int ID { get;set;}
public String Name { get;set;}
public int Age { get;set;}
}