1. 程式人生 > >數據綁定(五)使用集合對象作為列表控件的ItemsSource

數據綁定(五)使用集合對象作為列表控件的ItemsSource

http led student font ont bold pro edi com

原文:數據綁定(五)使用集合對象作為列表控件的ItemsSource

ItemsSource屬性可以接收一個IEnumerable接口派生類的實例作為自己的值,ItemsSource裏存放的是一條一條的數據,列表式控件的條目容器會為這些數據傳上外衣,只要為ItemsControl對象設置了ItemsSource屬性值,ItemsControl對象就會自動叠代其中的數據元素,為每一個數據元素準備一個條目容器,並使用Binding在條目容器與數據元素之間建立起關聯,例子:

界面代碼:

    <StackPanel Background="LightBlue">
        <TextBlock Text="Student ID:" FontWeight="Bold"></TextBlock>
        <TextBox x:Name="textBox1"></TextBox>
        <TextBlock Text="Student List:" FontWeight="Bold"></TextBlock>
        <ListBox x:Name="listBoxStudents" Height="110"></ListBox>
    </StackPanel>

後臺代碼:

        public MainWindow()
        {
            InitializeComponent();

            List<Student> stuList = new List<Student>()
            {
                new Student(){Id=0, Name="daijun", Age=11},
                new Student(){Id=1, Name="Tim", Age=12},
                new Student(){Id=2, Name="Tom", Age=13},
                new Student(){Id=3, Name="Kyle", Age=14},
                new Student(){Id=4, Name="Tony", Age=15}
            };

            listBoxStudents.ItemsSource = stuList;
            listBoxStudents.DisplayMemberPath = "Name";
            Binding binding = new Binding();
            binding.Source = listBoxStudents;
            binding.Path = new PropertyPath("SelectedItem.Id");
            textBox1.SetBinding(TextBox.TextProperty, binding);
        }


數據綁定(五)使用集合對象作為列表控件的ItemsSource