WPF数据绑定,参考代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Wpf数据绑定;

namespace Wpf数据绑定
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        MainWindow wd;   //构建函数传值
        //public Window1(MainWindow w)
        //{
        //    InitializeComponent();
        //    wd = w;

        //     aa.Text = wd.aaa.Text+wd.bbb.Password  ;   用窗口传值
        //}

        User1 us;  //对象实例化
        public Window1(User1 w)   //用这个类接收新对象
        {
            InitializeComponent();

            us = w;             
            aa.DataContext = w;        //获取或设置参与数据绑定时的数据的上下文。和前台进行绑定

            bb.SetBinding(TextBox.TextProperty,     //不需要和前台进行绑定,这一局代码就可是实现并显示
            new Binding("Pass") { Source = us, Mode = BindingMode.TwoWay });

  

            //aa.Text = w.Username;//这句代码为什么不行呢??????
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            
            us.Username = DateTime.Now.ToString("HH:mm:ss.fff");
        }
    }
}

类里的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace Wpf数据绑定
{
    public class User1 : INotifyPropertyChanged   //一个接口

    {
        private string code;

        public string Code
        {
            get { return code; }
            set { code = value; }
        }
        private string username;

        public string Username
        {
            get { return username; }
            set { 
                username = value;
                OnPropertyChanged("Username");  //调用下面的方法
            }
        }

       
        private string pass;

        public string Pass
        {
            get { return pass; }
            set { pass = value; }
        }

        public event PropertyChangedEventHandler PropertyChanged;   //用此种方法实现接口
        public virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    
    }
}


绑定的代码

原文地址:https://www.cnblogs.com/275147378abc/p/4606865.html