Form2.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Runtime.CompilerServices;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. namespace praktika6
  12. {
  13. public partial class Form2 : Form
  14. {
  15. public Form2()
  16. {
  17. InitializeComponent();
  18. Person person = new Person { Name = "Tom", Age = 18 };
  19. Label label1 = new Label();
  20. label1.Location = new Point(12, 10);
  21. label1.AutoSize = true;
  22. Controls.Add(label1);
  23. Label label2 = new Label();
  24. label2.Location = new Point(12, 40);
  25. label2.AutoSize = true;
  26. Controls.Add(label2);
  27. Button button = new Button();
  28. button.Location = new Point(12, 80);
  29. button.Text = "Change";
  30. button.AutoSize = true;
  31. Controls.Add(button);
  32. // изменяем свойство Name
  33. button.Click += (o, e) => person.Name = "admin";
  34. label1.DataBindings.Add(new Binding("Text", person, "Name", false, DataSourceUpdateMode.OnPropertyChanged));
  35. label2.DataBindings.Add(new Binding("Text", person, "Age", false, DataSourceUpdateMode.OnPropertyChanged));
  36. }
  37. }
  38. public class Person : INotifyPropertyChanged
  39. {
  40. string name = "";
  41. int age;
  42. public event PropertyChangedEventHandler? PropertyChanged;
  43. public string Name
  44. {
  45. get => name;
  46. set
  47. {
  48. if (name != value)
  49. {
  50. name = value;
  51. OnPropertyChanged();
  52. }
  53. }
  54. }
  55. public int Age
  56. {
  57. get => age;
  58. set
  59. {
  60. if (age != value)
  61. {
  62. age = value;
  63. OnPropertyChanged();
  64. }
  65. }
  66. }
  67. public void OnPropertyChanged([CallerMemberName] string prop = "")
  68. {
  69. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
  70. }
  71. }
  72. }