• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Monica2021
博客园    首页    新随笔    联系   管理    订阅  订阅

《深入详解WPF-刘铁锰》读书笔记 - 用集合作为列表控件的条目源ItemSource

集合→ 列表:使用集合对象作为列表控件的ItemSource

  • 列表式控件派生自ItemControl类,继承了ItemsSource属性,ItemsSource属性可以接收一个IEnumerable接口派生类的实例作为值(所有可被迭代遍历的集合都实现了这个接口,包括数组、List<T>deng )。
  • 每个ItemsControl的派生类都有自己对应的条目容器(Item Container)。ItemsSource里存放的是一条一条的数据,要想把数据显示出来需要为其穿上外衣——条目容器。
    //为ListBox设置Binding
    this.listBoxStudents.ItemSource=sutList;//stuList是准备好的数据源,Studentl类型列表
    
    this.listBoxStudents.DisplayMemberPath="Name";
    //当没有为ItemsControl显示地指定DataTemplate时,
    //SelectTemplate方法会为我们创建一个默认的最简单的DataTemplate,数据的“外衣”由DataTemplate穿上。 
    
    //为TextBox设置Binding 
    Binding binding=new Binding("SelectedItem.Id"){Source=this.listBoxStudents};//源和Path
    this.textBoxId.SetBing(TextBox.TextProperty,binding);//为目标设置Binding

     

  • 把C#代码中this.listBoxStudents.DisplayMemberPath="Name";删除,再在XAML中添加几行代码,ListBox的ItemTemplate属性(继承自ItemsControl类)的类型是DataTemplate。如下代码:
  • <ListBox x:Name="listBoxStudent" Height="150" Margin="5"> 
    <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Path=ID}" Width="30" />
                            <TextBlock Text="{Binding Path=Name}" Width="60"  />
                            <TextBlock Text="{Binding Path=Age}"  Width="30"/>
                            
                        </StackPanel>
                    </DataTemplate>
    </ListBox.ItemTemplate>
    </ListBox>
posted @ 2022-05-11 09:50  Monica2021  阅读(107)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3