Form1.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 Glava6
  12. {
  13. public partial class Form1 : Form
  14. {
  15. public Form1()
  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. public class Person : INotifyPropertyChanged
  38. {
  39. string name = "";
  40. int age;
  41. public event PropertyChangedEventHandler PropertyChanged;
  42. public string Name
  43. {
  44. get => name;
  45. set
  46. {
  47. if (name != value)
  48. {
  49. name = value;
  50. OnPropertyChanged();
  51. }
  52. }
  53. }
  54. public int Age
  55. {
  56. get => age;
  57. set
  58. {
  59. if (age != value)
  60. {
  61. age = value;
  62. OnPropertyChanged();
  63. }
  64. }
  65. }
  66. public void OnPropertyChanged([CallerMemberName] string prop = "")
  67. {
  68. PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
  69. }
  70. }
  71. private void Form1_Load(object sender, EventArgs e)
  72. {
  73. }
  74. }
  75. }