WPF(Binding集合对象数据源)

本文介绍了一个使用WPF ListBox控件进行数据绑定的例子。通过创建一个包含学生信息的列表,并将其绑定到ListBox中,展示了如何实现数据源的动态显示。同时,还实现了TextBox与ListBox的联动效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<Window x:Class="TestOfBindingItemsControl.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">
    <StackPanel x:Name="stackPanel" Background="LightBlue" >
        <TextBlock Text="StudentID:" Margin="5" />
        <TextBox x:Name="textBoxId" Margin="5" />
        <TextBlock Text="StudentList:" FontWeight="Bold"
                   Margin="5" />
        <ListBox x:Name="listBoxStudents" 
                 Height="110" 
                 Margin="5"
                 />
        
    </StackPanel>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TestOfBindingItemsControl
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            List<Student> stuList = new List<Student>()
            {
                  new Student(){Id = 0,Name = "Tim",Age = 29},
                  new Student(){Id = 1,Name = "Tom",Age = 28},
                  new Student(){Id = 2,Name = "Kyle",Age = 27},
                  new Student(){Id = 3,Name = "Tony",Age = 26},
                  new Student(){Id = 4,Name = "Vine",Age = 25},
                  new Student(){Id = 5,Name = "Mike",Age = 24}     
            };

            // 为ListBox设置Binding
            this.listBoxStudents.ItemsSource = stuList;
            this.listBoxStudents.DisplayMemberPath = "Name";

            Binding binding = new Binding("SelectedItem.Id")
                                  {
                                      Source = this.listBoxStudents
                                  };

            this.textBoxId.SetBinding(TextBox.TextProperty, binding);
        }
    }

    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }
    }
}


转载于:https://www.cnblogs.com/wjchang/archive/2013/04/08/3671675.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值