XAML is indeed a good thing, with a strong sense of attention and a clear view. The following is an example of a ComboBox:
< ComboBox Height = "23" Horizontalalignment = "Left" Margin = "0, 11, 0, 0" Name = "Combox1" Verticalalignment = "TOP" Width = "120" Itemssource =" {Binding} " Selectedindex = "0" >
< ComboBox. itemtemplate >
< Datatemplate >
< Textblock Text =" {Binding Path = Name} " />
</ Datatemplate >
</ ComboBox. itemtemplate >
</ ComboBox >
When binding, you only need to specify its datacontext as a datatable instance.
XAML is concise and refined, so let's take a look at C #CodeHow does one bind a ComboBox? See the following example to add a ComboBox dynamically:
Private Void Window_loaded ( Object Sender, routedeventargs E)
{
Datatable dt = New Datatable ();
DT. Columns. Add ( " Name " );
DT. Rows. Add ( " Just " );
DT. Rows. Add ( " For " );
DT. Rows. Add ( " Test " );
ComboBox CMB = New ComboBox ();
CMB. Width = 120 ;
CMB. Height = 50 ;
Datatemplate = New Datatemplate ();
Frameworkelementfactory F = New Frameworkelementfactory ( Typeof (Textblock ));
F. setbinding (textblock. textproperty, New Binding ( " Name " ));
Datatemplate. visualtree = F;
CMB. itemtemplate = Datatemplate;
CMB. itemssource = DT. defaultview;
Grid. Children. Add (CMB );
}
Note that when you specify the datatable data source for the dynamically generated ComboBox itemssource,
You cannot directly specify CMB. itemssource = DT. Rows; instead, you must use CMB. itemssource = DT. defaultview;
Otherwise, you will find that the data is bound, but it is not displayed. This is what I cannot figure out. If you understand this knowledge, please kindly advise. Thank you.