数据绑定(五)使用集合对象作为列表控件的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);
        }


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值