WPF绑定ListBox

class Student
    {
        public string sno { get; set; }
        public string sname { get; set; }
        public string sage { get; set; }
    }

定义实体类Student



        <ListBox Height="163" HorizontalAlignment="Left" Margin="12,12,0,0" Name="listBox1" VerticalAlignment="Top" Width="217" >            
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding sno}"/>
                        <TextBlock Text="{Binding sname}"/>
                        <TextBlock Text="{Binding sage}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

XAML页面设置绑定格式和字段

List<Student> students = new List<Student>();
            students.Add(new Student { sno = "1", sname = "王井", sage = "20" });
            students.Add(new Student { sno = "2", sname = "高瑞", sage = "21" });
            students.Add(new Student { sno = "3", sname = "刘欢", sage = "21" });
            listBox1.Items.Clear();
            listBox1.ItemsSource = students;


后台绑定数据

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF ListBox 绑定模板指的是在 ListBox 中使用数据绑定绑定数据源,并使用自定义的模板来呈现数据。 以下是实现 WPF ListBox 绑定模板的步骤: 1. 创建数据源:创建一个集合类,用于存储数据源。 2. 绑定数据源:使用 ListBox 的 ItemsSource 属性将数据源绑定ListBox 控件上。 3. 创建数据模板:通过创建一个 DataTemplate 对象来定义自定义模板。 4. 应用模板:使用 ListBox 的 ItemTemplate 属性将模板应用到 ListBox 控件上。 下面是一个示例代码,演示如何实现 WPF ListBox 绑定模板: ``` <Window x:Class="WpfApp1.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 ItemsSource="{Binding Students}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Name}" /> <TextBlock Text="{Binding Age}" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> ``` 在上述代码中,我们创建了一个 ListBox 控件,并将它的 ItemsSource 属性绑定到一个名为 Students 的集合类上。然后,我们创建了一个 DataTemplate 对象,并在其中定义了一个 StackPanel 和两个 TextBlock 控件,用于显示每个学生的姓名和年龄。最后,我们将模板应用到 ListBox 中,以便呈现数据。 注意:在代码中,我们使用了数据绑定和 MVVM 模式,这里不再赘述。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值