一、DataGrid是專(zhuān)門(mén)用來(lái)顯示列表的控件,而且可以根據(jù)數(shù)據(jù)格式自動(dòng)生成對(duì)應(yīng)格式的列表(僅限簡(jiǎn)單的數(shù)據(jù)格式比如字符串怯晕、布爾值等),還可以在列表下方新建一條數(shù)據(jù)缸棵,這里使用了DataGrid最基本的功能:自動(dòng)生成列舟茶,禁止用戶增加數(shù)據(jù)。
二堵第、MainWindow設(shè)置數(shù)據(jù)上下文吧凉,然后在DataGrid的ItemsSource屬性中設(shè)置綁定students屬性,然后在MainWindow類(lèi)中定義它型诚,添加幾條數(shù)據(jù)客燕。
MainWindow.xaml.cs文件代碼
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
namespace WpfApp3
{
/// <summary>
/// MainWindow.xaml 的交互邏輯
/// </summary>
public partial class MainWindow : Window
{
public Students students { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this; //設(shè)置窗口數(shù)據(jù)上下文為當(dāng)前對(duì)象鸳劳,DataGrid控件會(huì)自動(dòng)查找到students屬性
students = new Students();
//添加幾條數(shù)據(jù)
students.Add(new Student { IsGood = false, Name = "Tom" });
students.Add(new Student { IsGood = false, Name = "Peter" });
students.Add(new Student { IsGood = true, Name = "Hank" });
students.Add(new Student { IsGood = false, Name = "Nancy" });
students.Add(new Student { IsGood = true, Name = "Tom" });
}
}
public class Student
{
public string Name { get; set; }
public bool IsGood { get; set; }
}
public class Students: ObservableCollection<Student>{}
}
MainWindow.xaml文件代碼
<Window x:Class="WpfApp3.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:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<DataGrid ItemsSource="{Binding students}" HorizontalAlignment="Left" Height="293"
Margin="110,62,0,0" VerticalAlignment="Top"
AutoGenerateColumns="True"
CanUserAddRows="False"/>
</Grid>
</Window>
代碼效果如下:
代碼效果