Do not think that the data binding in WPF is complex, although it is indeed better than winformProgramIt is more flexible, but its essence remains unchanged. In particular, the ComboBox control, we know that in winform, the control has two attributes set specifically for data binding-displaymenber and valuemenber, bind fields for display and for storing user-selected values. The most typical applications are data fields in the form of key-value, such as student ID and Student name in the student table.
In fact, the logic is the same in WPF. Come on, let's get started.
You don't need to talk about how to create an application. 33 words are omitted.
Drag and Drop a ComboBox control and a button in the window to check the selected value.
SwitchCodeView, which defines an employee class and a list.
Public class employee {public string name {set; get;} public int empid {set; get;} public class employeearr: observablecollection <employee> {public employeearr () {This. add (new employee {empid = 1, name = ""}); this. add (new employee {empid = 2, name = "Xiao Hu"}); this. add (new employee {empid = 3, name = ""}); this. add (new employee {empid = 4, name = "calf X"}); this. add (new employee {empid = 5, name = ""});}}
Then add the resource list to the XAML.
<Window xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml" X: class = "combobox_binding_sample.mainwindow" X: name = "window" Title = "mainwindow" width = "200" Height = "120" xmlns: c = "CLR-namespace: combobox_binding_sample"> <window. resources> <C: employeearr X: Key = "empcols"/> </window. resources> ....... </WINDOW>
Then, bind the ComboBox to the set in the resource.
<ComboBox X: Name = "CMB" margin = "8, 8, 7.04 "itemssource =" {staticresource empcols} "displaymemberpath =" name "selectedvaluepath =" empid "/> <button margin =" 28, 6, 28, 6 "content =" show selected value "grid. row = "1" Click = "button_click"/>
Click Event of the final completion button
Private void button_click (Object sender, routedeventargs e) {If (this. CMB. selectedindex! =-1) {MessageBox. Show ("the employee ID you selected is \ n" + CMB. selectedvalue );}}
Run it to get the effect.
As we have just discussed the dependency attribute in the previous article, we may also use its real-time update function here.
In this way, as long as the selected item changes, the employee ID is displayed in the text block in real time.