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(); 
       } 
}
posted @ 2016-12-03 18:59  高山百川  阅读(6385)  评论(0编辑  收藏  举报