首页 > 代码库 > 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的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。