1.定义实体,实现接口:INotifyPropertyChanged和INotifyPropertyChanging
public class Course : INotifyPropertyChanged, INotifyPropertyChanging
{
private int _id;
public int Id
{
get { return _id; }
set
{
if (_id != value)
{
RaisePropertyChanging("Id");
_id = value;
RaisePropertyChanged("Id");
}
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
RaisePropertyChanging("Name");
_name = value;
RaisePropertyChanged("Name");
}
}
}
private string _location;
public string Location
{
get { return _location; }
set
{
if (_location != value)
{
RaisePropertyChanging("Location");
_location = value;
RaisePropertyChanged("Location");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangingEventHandler PropertyChanging;
private void RaisePropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
}
2.页面绑定数据
<!--ContentPanel - 在此处放置其他内容-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="课程名称" Grid.Row="0" Grid.Column="0"/>
<TextBox Text="{Binding Name,Mode=TwoWay}" Grid.Column="1"/>
<TextBlock Text="上课地点" Grid.Row="1" Grid.Column="0"/>
<TextBox Text="{Binding Location,Mode=TwoWay}" Grid.Row="1" Grid.Column="1"/>
</Grid>
// 构造函数
public MainPage()
{
InitializeComponent();
Course c = new Course()
{
Name = "电子商务",
Location = "教学楼403"
};
// this.DataContext = c; 当前页面绑定上下文
this.ContentPanel.DataContext = c; //Grid空间绑定上下文
}