WPF中ListBox的绑定

WPF中列表式控件派生自ItemsControl类,继承了ItemsSource属性。ItemsSource属性可以接收一个IEnumerable接口派生类的实例作为自己的值(所有可被迭代遍历的集合都实现了这个接口,如数组、List<T>等)。每一个 ItemsControl的派生类都有自己的条目容器,如ListBox的条目容器ListBoxItem.当我们利用Binding为一个ItemsControl设置了ItemsSource属性值,ItemsControl对象会自动迭代其中的数据元素,并为每个数据元素准备一个条目容器。
下面的例子,为ListBox绑定了一个List<T>类型的数据源,并在编写框中显示选中的Student对象的ID。

界面效果如下:

XAML文件代码:

<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="350" 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="23" HorizontalAlignment="Left" Margin="12,61,0,0" Name="textBox1" VerticalAlignment="Top" Width="120"   
                 Text="{Binding SelectedItem.ID,ElementName=listBox1}"/>  
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,32,0,0" Name="textBlock1" Text="Student ID:" VerticalAlignment="Top" />  
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,106,0,0" Name="textBlock2" Text="Student List:" VerticalAlignment="Top" />  
    </Grid>  
</Window>  

这里需要说明一下的是ListBox的DisplayMemberPath属性,顾名思义,其函数是ListBox中需要显示的的绑定对象的Path,而SelectedValuePath,意思是在选中某个Item时我们可以通过ListBox的SelectedValue属性获取的值的类型,如选中了张三,则通过SelectedValue我们可以获取张三的ID。
每一个派生自ItemsControl类的类都具有上述属性,包括ListView、ListBox、ComBox、TreeView等等。

public partial class MainWindow : Window  
    {  
        public MainWindow()  
        {  
            InitializeComponent();  
  
            List<Student> stuList = new List<Student>()  
            {  
                new Student(){ID=1,Name="张?三¨y"},  
                 new Student(){ID=2,Name="李¤?四?"},  
                  new Student(){ID=3,Name="王ª?五?"}  
            };  
  
            this.listBox1.ItemsSource = stuList;  
        }  
    }  
    public class Student  
    {  
        public int ID { get; set; }  
        public string Name { get; set; }  
    }  

猜你喜欢

转载自blog.csdn.net/u014453443/article/details/89710758