WPF Demo6

通知项熟悉、数据绑定

using System.ComponentModel;

namespace Demo6
{
    /// <summary>
    /// 通知项属性
    /// </summary>
    public class Student : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string name;

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
                }
            }
        }
    }
}

using System.ComponentModel;

namespace Demo6
{
    public class MainWindowModele : INotifyPropertyChanged
    {
        private string _name = "张三";
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }

        public MainWindowModele()
        {
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

  

<Window x:Class="Demo6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <!--绑定是一种自动机制-->
        <TextBox x:Name="txtTest" Text="{Binding Name,Mode=TwoWay}"  Margin="5"/>
        <Button x:Name="btnTest" Margin="10" Width="75" Height="50" Content="add age" Click="btnTest_Click"/>
        <TextBox x:Name="txtTest2" Text="{Binding ElementName=txtTest,Path=Text, Mode=TwoWay}"  Margin="5"/>
        <TextBox x:Name="txtTest3" Text="{Binding ElementName=txtTest2,Path=Text, Mode=TwoWay}"  Margin="5"/>
    </StackPanel>
</Window>
using System.Windows;

namespace Demo6
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Student stu = new Student();

        public MainWindow()
        {
            InitializeComponent();

            MainWindowModele mwm = new MainWindowModele();
            this.DataContext = mwm;

            //方式一
            //Binding b = new Binding();
            //b.Source = stu;
            //b.Path = new PropertyPath("Name");
            //BindingOperations.SetBinding(this.txtTest,TextBox.TextProperty,b);

            //方式二
            //   this.txtTest.SetBinding(TextB.Te//xtProperty, new Binding("Name") { Source = stu = new Student() });
        }

        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            stu.Name += "110";
        }
    }
}

原文地址:https://www.cnblogs.com/YYkun/p/6867125.html