A list-style control in WPF derives from the ItemsControl class and inherits the ItemsSource property. The ItemsSource property can receive an instance of a IEnumerable interface derived class as its own value (all collections that can be iterated through are implemented with this interface, such as arrays, list<t>, and so on). Each itemscontrol derived class has its own item container, An entry container such as a ListBox ListBoxItem. When we use the binding to set the ItemsSource property value for a ItemsControl, the ItemsControl object automatically iterates over the data element and prepares an entry container for each data element.
In the following example, a data source of type list<t> is bound to a ListBox and the ID of the selected student object is displayed in the Write box.
The interface effect is as follows:
XAML File code:
[HTML]View PlainCopyprint?
- <window x:class="_6_15.mainwindow"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="Http://schemas.microsoft.com/winfx/2006/xaml"
- title="MainWindow" height= "width=" 525 ">
- <Grid>
- <ListBox height= "164" horizontalalignment="left" margin="12,0,0,12" name= "ListBox1" verticalalignment="Bottom" width="471 "
- displaymemberpath= "Name" selectedvaluepath= "ID" />
- <TextBox height= "horizontalalignment=" "left " margin="12,61,0,0" name= "TextBox1" verticalalignment="Top" width="
- text="{Binding selecteditem.id,elementname=listbox1}"/>
- <TextBlock height= "all" Horizontalalignment= "left" margin=" 12,32,0,0 " name=" TextBlock1 " text= "Student id:" verticalalignment= "Top" />
- <TextBlock height="horizontalalignment=" "left " margin="12,106,0,0" name= "TextBlock2" text="Student List:" verticalalignment="Top" />
- </Grid>
- </Window>
What you need to illustrate here is the DisplayMemberPath property of the ListBox, as its name implies, its function is the path of the bound object that needs to be shown in the ListBox, and SelectedValuePath, This means that when we select an item we can get the type of the value through the SelectedValue property of the ListBox, if Zhang San is selected, we can get the Zhang San ID by SelectedValue.
Each class derived from the ItemsControl class has the above attributes, including the ListView, ListBox, Combox, TreeView, and so on.
[CSharp]View PlainCopyprint?
- Public partial class Mainwindow:window
- {
- Public MainWindow ()
- {
- InitializeComponent ();
- list<student> stulist = new list<student> ()
- {
- New Student () {id=1,name="Zhang Three ¨y"},
- New Student () {id=2,name="LI ¤ four?"},
- New Student () {id=3,name="Wang a five?"}
- };
- This.listBox1.ItemsSource = stulist;
- }
- }
- public class Student
- {
- public int ID { get; set;}
- public string Name { get; set;}
- }
Bindings for a ListBox in WPF