WPF 變量綁定實現


  最近初學WPF,遇到如控件的內容是動態生成的。這時候就需要變量綁定。

  簡單寫下變量綁定的步驟。

  如下面的 例子,TextBlock 的內容是動態的,綁定變量StuName。

<TextBlock x:Name="textBlock1" Grid.Column="7" 
    HorizontalAlignment="Left" Margin="68.205,6,0,96" 
    Grid.Row="3" TextWrapping="Wrap" 
    Text="{Binding Path=StuName}" Width="70"  
    Background="#3387FE" Foreground="#FFFFFF" 
    Grid.ColumnSpan="3" />

 新建一個Student類並繼承。

 public class Student: INotifyPropertyChanged
    {
        private string stuName;

        public string StuName
        {
            get
            {
                return stuName;
            }

            set
            {
                stuName = value;
            }
        }

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

 動態賦值的地方

public partial class MainWindow : Window
{
      private Stduent m_student = null;

       public void InitStudent()
       {
            m_student   = new Stduent();
            m_student.StuName = "Zhangsan";
            this.textBlock1.DataContext = m_student; 
       } 
       public China() 
       { 
            InitializeComponent(); 
    InitStudent(); 
       } 
}


免責聲明!

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



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