首页 > 代码库 > WPF DataGrid的使用

WPF DataGrid的使用

构造数据:

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 WpfApplication2{    /// <summary>    /// MainWindow.xaml 的交互逻辑    /// </summary>    public partial class MainWindow : Window    {        Random rnd = new Random();        public MainWindow()        {            InitializeComponent();           var tlist = new List<Person>();            for (int i = 0; i < 10; i++)            {                tlist.Add(new Person()                {                    Name = "张三" + i,                    Age = rnd.Next(20)                });            }           list= tlist.Select(x => new { x, id = Guid.NewGuid() }).OrderBy(y => y.id).Select(z => z.x).ToList<Person>();            this.DataContext = this;        }        public List<Person> list { get; set; }    }    public class Person    {        public string Name { get; set; }        public int Age { get; set; }    }}

界面显示:

<Window x:Class="WpfApplication2.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="MainWindow" Height="850" Width="525">    <StackPanel>        <ListBox ItemsSource="{Binding list}" DisplayMemberPath="Name"></ListBox>        <DataGrid Name="dg" AutoGenerateColumns="False" ItemsSource="{Binding list}" CanUserAddRows="False">            <DataGrid.Columns>                <DataGridTextColumn Binding="{Binding Name}" Width="100" Header="名称" />                <DataGridTextColumn Binding="{Binding Age}" Header="年龄" />            </DataGrid.Columns>        </DataGrid>        <TextBlock Text="{Binding ElementName=dg,Path=SelectedItem.Name}"></TextBlock>    </StackPanel></Window>

技术分享

WPF DataGrid的使用