Recently beginner WPF, encountering content such as controls that are dynamically generated. Variable binding is required at this time.
Simply write down the steps of the variable binding.
As the following example, the content of TextBlock is dynamic, and the binding variable is 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= "All" background= "#3387FE" foreground= "#FFFFFF" grid.columnspan= "3"/>
Create a new student class and inherit it.
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)) ; } }}
Places for dynamic assignment of values
Public Partial classmainwindow:window{PrivateStduent m_student =NULL; Public voidinitstudent () {m_student=Newstduent (); M_student. Stuname="Zhangsan"; This. Textblock1.datacontext =m_student; } PublicChina () {InitializeComponent (); Initstudent (); } }
WPF Variable Binding implementation