zoukankan      html  css  js  c++  java
  • WPF 双向绑定

    定义类: 类实现INotifyPropertyChanged 接口

     1 using Microsoft.Win32;
     2 using System.ComponentModel;
     3 using System.Windows;
     4 
     5 namespace WPFEntity
     6 {
     7     public class Person : INotifyPropertyChanged
     8     {
     9         private int age;
    10 
    11         public event PropertyChangedEventHandler PropertyChanged;
    12 
    13         public int Age
    14         {
    15             get { return this.age; }
    16             set
    17             {
    18                 this.age = value;
    19                 if (this.PropertyChanged != null)
    20                 {
    21                     this.PropertyChanged(this, new PropertyChangedEventArgs("Age"));
    22                 }
    23             }
    24         }
    25 
    26         public string Name { get; set; }
    27     }
    28 }

    .cs文件绑定:

    public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                this.Loaded += MainWindow_Loaded;
                btnAddAge.Click += btnAddAge_Click;
            }
    
            Person person = new Person();
    
            void MainWindow_Loaded(object sender, RoutedEventArgs e)
            {
                person.Name = "Nelson";
                person.Age = 24;
                grid1.DataContext = person;
            }
    
            void btnAddAge_Click(object sender, RoutedEventArgs e)
            {
                person.Age++;
            }
        }

    XAML代码:

    <TextBox Name="txtName" Text="{Binding Name}" HorizontalAlignment="Left" Height="23" Margin="83,74,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <TextBox Name="txtAge" Text="{Binding Age}" HorizontalAlignment="Left" Height="23" Margin="83,131,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
    <Button Name="btnAddAge" Content="Age增加" HorizontalAlignment="Left" Margin="274,75,0,0" VerticalAlignment="Top" Width="75"/>
            
    分享每天的收获之一种快乐。
  • 相关阅读:
    Loj #6560 小奇取石子
    某谷 P5153 简单的函数
    某谷 P5159 WD与矩阵
    前端ajax访问 django 报错 POST http://127.0.0.1:8001/xxx 403 (Forbidden)
    python
    Java
    Java
    Java
    Java
    java web 向数据库插入中文数据乱码问题
  • 原文地址:https://www.cnblogs.com/TXZkuaizi/p/WPF_Binding.html
Copyright © 2011-2022 走看看