WPF——ListBox创建并连接后台数据

对如何通过WPF来创建一个listBox,并同后台数据链接,做一个简单的样例介绍。

首先现在XAML中创建一个ListBox并给个名字,以便在CS中引用到他。

<Window x:Class="listBox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:listBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ListBox Name="listBoxEmployee" Margin=" 5"/>
    </Grid>
</Window>

在CS中先定义一个employee类,并创建一个包含多个employee对象的list。再把list赋予给listBox且对要显示的对象属性进行一个声明。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 listBox
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //this.listBoxEmployee.SelectedValuePath = "id";
            //把list和listBox做一个连接
            this.listBoxEmployee.ItemsSource = emplist;
            //DisplayMemberPath告诉listBox应该显示list中每个对象的哪个属性
            this.listBoxEmployee.DisplayMemberPath = "name";

        }


        //创建一个employee对象的list
        List<Employee> emplist = new List<Employee>()
        {
                new Employee(){id = 11,name = "aaaa",age = 21 },
                new Employee(){id = 2,name = "bbb",age = 22 },
                new Employee(){id = 3,name = "ccc",age = 23 },
                new Employee(){id = 4,name = "ddd",age = 24 },
                new Employee(){id = 5,name = "eeee",age = 25 },
                new Employee(){id = 6,name = "ffff",age = 26 },
                new Employee(){id = 7,name = "gggg",age = 27 },
                new Employee(){id = 8,name = "hhh",age = 28 },
                new Employee(){id = 9,name = "iii",age = 29 },
                new Employee(){id = 10,name = "jjjj",age = 30 }
        };


        //创建一个Employee的类
        public class Employee
        {
            public int id { get; set; }
            public string name { get; set; }
            public int age { get; set; }
        }

    }
}

注:当代码复杂时,可以把类的定义以及list的生成换到别的位置,来优化下代码的可读性。

上一篇:nim_duilib(6)之listbox


下一篇:WPF进阶技巧和实战03-控件(5-列表、树、网格01)