WPF 精修篇 数据绑定 更新通知

原文: WPF 精修篇 数据绑定 更新通知

开始更新一点有意思的了

首先 数据绑定  其中之一 Element 绑定

看例子


  
  
  1. <Window x:Class= "WpfApplication20.MainWindow"
  2. xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x= "http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title= "MainWindow" Height= "156.383" Width= "246.489" x:Name= "MWindow">
  5. <Grid>
  6. <TextBox HorizontalAlignment= "Left" Height= "23" Margin= "30,48,0,0" TextWrapping= "Wrap" VerticalAlignment= "Top" Width= "120" Text= "{Binding ElementName=MWindow,Path=PresonName}"/>
  7. <TextBlock HorizontalAlignment= "Left" Margin= "30,16,0,0" TextWrapping= "Wrap" VerticalAlignment= "Top" Width= "42" Text= "部门:"/>
  8. <Button Content= "提交" HorizontalAlignment= "Left" Margin= "30,85,0,0" VerticalAlignment= "Top" Width= "75" Click= "Button_Click"/>
  9. <Button Content= "重置" HorizontalAlignment= "Left" Margin= "127,85,0,0" VerticalAlignment= "Top" Width= "75" Click= "Button_Click_1"/>
  10. <TextBlock HorizontalAlignment= "Left" Margin= "85,16,0,0" TextWrapping= "Wrap" VerticalAlignment= "Top" Text= "{Binding ElementName=MWindow,Path=Department}"/>
  11. </Grid>
  12. </Window>

  
  
  1. public partial class MainWindow : Window, INotifyPropertyChanged
  2. {
  3. public MainWindow()
  4. {
  5. InitializeComponent();
  6. }
  7. private string department;
  8. public string Department
  9. {
  10. get { return "软件开发"; }
  11. }
  12. private string presonName;
  13. public string PresonName
  14. {
  15. get { return presonName; }
  16. set { presonName = value;
  17. OnPropertyChanged( "PresonName");
  18. }
  19. }
  20. private void Button_Click(object sender, RoutedEventArgs e)
  21. {
  22. MessageBox.Show( "Hi," + PresonName);
  23. }
  24. private void Button_Click_1(object sender, RoutedEventArgs e)
  25. {
  26. PresonName = "";
  27. }
  28. #region INotifyPropertyChanged 成员
  29. public event PropertyChangedEventHandler PropertyChanged;
  30. public void OnPropertyChanged(string name)
  31. {
  32. if(PropertyChanged!= null){
  33. PropertyChanged.Invoke( this, new PropertyChangedEventArgs(name));
  34. }
  35. }
  36. #endregion
  37. }

我们在这个例子里有俩个操作

一个是数据绑定

一个是数据通知

绑定 是用Element 指定window 窗体 因为 创建属性以后 window 窗体就有这个属性 通过名字.属性的方式

通知 需要继承 INotifyPropertyChanged

实现接口方法

  public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string name) 
        {
            if(PropertyChanged!=null){
            PropertyChanged.Invoke(this,new PropertyChangedEventArgs(name));
            }
        }

在需要通知的属性下面  加上

OnPropertyChanged(“”属性名“”);

就可以起到通知作用

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12075441.html
今日推荐