在wpf界面中为了显示数据方便,我将界面上的TextBox都绑定到了一个类的某些属性上,例如,我有个Student类,
class Student
{
public string Name;
public string No;
public string CnScore;
public string EnScore;
public string MathScore;
}
界面上的几个编辑框,用于显示数据:
<Grid Name="girdMain">
<TextBox x:Name="txtName" Text="{Binding Path=Name}">                    
<TextBox x:Name="txtNo" Text="{Binding Path=No}"> 
<TextBox x:Name="txtCnScore" Text="{Binding Path=CnScore}">
<TextBox x:Name="txtEnScore" Text="{Binding Path=EnScore}">
<TextBox x:Name="txtMathScore" Text="{Binding Path=MathScore}"> 
</Grid>程序的处理:当程序中查询到每个student时,将student传给Grid.DataContext,这样界面中的TextBox就会根据绑定路径显示数据;
 如:Student student=GetStudentFormDB();
girdMain.DataContext=student;
这样显示数据确实很方便,但是,如果我要方向的通过TextBox获取数据貌似还是像以前没有绑定那样一样麻烦,
如果先给Grid.DataContext赋值绑定了数据,
那可以使用Student stu=(Student)girdMain.DataContext;这样获取修改后的数据,但是如果事先没有进行这步:Student student=GetStudentFormDB();
girdMain.DataContext=student;
然后Student stu=(Student)girdMain.DataContext;是获取不到数据的,那这样获取数据是不是只能通过最原始的办法,一个TextBox一个TextBox的获取数据,然后再组装类呢?
请问这里有没有比较好的处理方法?

解决方案 »

  1.   

    不知你的数据模型是否实现了INotifyPropertyChanged接口,一般实现的话只需赋一次值:girdMain.DataContext=student就可以了。然后后面的随时变动,你只需去读student对象就可以了。    public class Student : INotifyPropertyChanged
         {
             //实现接口
             public event PropertyChangedEventHandler PropertyChanged;
     
             public void OnChangedProperties(string propertyName)
             {
                 if (this.PropertyChanged != null)
                 {
                     this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
                 }
             }  
     
             //属性
             private string name;
     
             public string Name
             {
                 get { return this.name; }
     
                 set
                 {
                     this.name = value;
     
                     this.OnChangedProperties(@"Name");
                 }
             }
    //其他属性类似  
         }