WPF 數據綁定(Binding)(一)-自定義類作為源(Source)


一、自定義類作為源綁定到TextBlock

1.新建一個Student類

public class Student
    {
        public Student(string name)
        {
            this.Name = name;
        }
        public string Name { get; set; }
        
    }

2.將Student的Name屬性綁定到TextBlock

        
     Student Stu = new Student("Pitter");
     //在窗體的構造函數中綁定 public MainWindow() { InitializeComponent(); Binding bind = new Binding(); bind.Source = student; bind.Path = new PropertyPath("Name"); //指定Binding 目標和目標屬性 tbName.SetBinding(TextBlock.TextProperty, bind); }

    運行效果如下:

3.但此時的Name屬性不具備通知Binding的能力,即當數據源(Stu的Name屬性)發生變化時,Binding不能同時更新目標的中數據

    添加一個Button按鈕驗證

Student Stu = new Student("Pitter");
        //在窗體的構造函數中綁定
        public MainWindow()
        {
            InitializeComponent();           
            Binding bind = new Binding();
            bind.Source = Stu;
            bind.Path = new PropertyPath("Name");
            //指定Binding 目標和目標屬性
            tbName.SetBinding(TextBlock.TextProperty, bind);
        }

        private void btName_Click(object sender, RoutedEventArgs e)
        {
            Stu.Name = "Harry";
        }

    此時點擊Button按鈕時,TextBlock內容不會發生任何變化

解決方法就是給Student類實現一個接口:INotifyPropertyChanged(位於命名空間:System.ComponentModel)

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

public event PropertyChangedEventHandler PropertyChanged; }

    這時再點擊按鈕文本就會發生改變

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM