<Label x:Name="lbScore1" Content="{Binding Score1, Mode=TwoWay}" Width="200" FontSize="15" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/> <Label x:Name="lbScore2" Content="{Binding Score2, Mode=TwoWay}" Width="200" FontSize="15" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/> <Label x:Name="lbScore3" Content="{Binding Score3, Mode=TwoWay}" Width="200" FontSize="15" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/> <Label x:Name="lbScore4" Content="{Binding Score4, Mode=TwoWay}" Width="200" FontSize="15" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/> <Label x:Name="lbScore5" Content="{Binding Score5, Mode=TwoWay}" Width="200" FontSize="15" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"/>
1.UI界面里面的Label绑定数据,双向绑定用TwoWay,默认为OneWay,这儿必须加上Mode=TwoWay。
public class UserScore : INotifyPropertyChanged { private string userName; private string score1; private string score2; private string score3; private string score4; private string score5; public string UserName { get { return userName; } set { this.userName = value; } } public string Score1 { get { return score1; } set { this.score1 = value;//value转到定义,?其实就是public int age//这里暂时不知道这种机制 if (PropertyChanged != null)//如果没有点击实现接口,就没有propertychanged这个成员 { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(Score1)); } } } public string Score2 { get { return score2; } set { this.score2 = value; if (PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(Score2)); } } } public string Score3 { get { return score3; } set { this.score3 = value; if (PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(Score3)); } } } public string Score4 { get { return score4; } set { this.score4 = value; if (PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(Score4)); } } } public string Score5 { get { return score5; } set { this.score5 = value; if (PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(Score5)); } } } public event PropertyChangedEventHandler PropertyChanged; }
2.后台类代码:必须为INotifyPropertyChanged接口类, public class UserScore : INotifyPropertyChanged //在此要选择INotifyPropertyChanged,右键,解析得到命名空间,但还要增多一步:选择INotifyPropertyChanged,右键,实现接口。
private void BindingData() { for (int i = 0; i < 10; i++) { ctlList[i].lbScore1.DataContext = scoreList[curPage * 10 + i]; ctlList[i].lbScore2.DataContext = scoreList[curPage * 10 + i]; ctlList[i].lbScore3.DataContext = scoreList[curPage * 10 + i]; ctlList[i].lbScore4.DataContext = scoreList[curPage * 10 + i]; ctlList[i].lbScore5.DataContext = scoreList[curPage * 10 + i]; } }
3.cs后台添加数据绑定对象,scoreList链表里面存放的是UserScore接口类,ctlList存放的是控件。这样就实现了双向数据绑定,任何一方改变都会有更新,在通过数据库数据对接,就基本上实现了数据的双向通信。