1.创建 DataGrid
<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="15,195,0,0" VerticalAlignment="Top" Height="320" Width="400" AutoGenerateColumns="False">
</DataGrid>
2.列名设置
在WPF中对DataGrid控件的列名设置是非常简单方便的,跟WPF的所有控件都一样可以对某个元素的独立控制 ,所以对DataGrid的列名设置也不例外,我们到<DataGrid.Columns>进行设置即可。
<DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="15,195,0,0" VerticalAlignment="Top" Height="320" Width="400" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="姓名" Binding="{Binding Name}" Width="80" />
<DataGridTextColumn Header="性别" Binding="{Binding SaturationAmout}" Width="80" />
<DataGridTextColumn Header="年龄" Binding="{Binding RealTimeAmout}" Width="80"/>
<DataGridTextColumn Header="生日" Binding="{Binding SumAmout}" Width="150"/>
</DataGrid.Columns>
</DataGrid>
在<DataGridTextColumn> 中的 Header 就是设置的列名了,如: Header="实时数据"
3.数据绑定
---------------------------------------------前台代码----------------------------------------------
(1)在资源视图xml文件的DataGrid,并设置绑定。
<DataGrid x:Name="DATA_GRID" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="15,195,0,0" VerticalAlignment="Top" Height="320" Width="400" AutoGenerateColumns="False" BorderBrush="#FF96B8D8" IsSynchronizedWithCurrentItem="False" SelectionChanged="DATA_GRID_SelectionChanged" >
<DataGrid.Columns>
<DataGridTextColumn Header="姓名" Width="80" Binding="{Binding name}"/>
<DataGridTextColumn Header="性别" Width="80" Binding="{Binding sex}"/>
<DataGridTextColumn Header="年龄" Width="80" Binding="{Binding age}"/>
<DataGridTextColumn Header="生日" Width="150" Binding="{Binding birthday}"/>
</DataGrid.Columns>
</DataGrid>
ItemsSource="{Binding}" 和Binding="{Binding name}" Binding="{Binding sex}"进行数据绑定,其中name和age是对应的属性名。
(2)如果要让DataGridComboBoxColumn中下拉列表的内容为制定枚举类型的内容,则要指定静态资源。这样,整个xaml文件应进行设置:
Title="我的窗口" Height="577" Width="839" Loaded="LoadData">
其中LoadData是添加数据的方法名。
---------------------------------------------后台代码----------------------------------------------
(3)在项目中创建一个people类,并写get,set方法。
//people类
public class people
{
public string name { get; set; }
public string sex { get; set; }
public string age { get; set; }
public string birthday { get; set; }
}
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
//创建people数组
ObservableCollection<people> peopleList = new ObservableCollection<people>();
public MainWindow()
{
InitializeComponent();
}
注意:如果不写get,set,数据将不会加载到DataGrid中
(4)实现数据添加
//创建dataGrid数据
private void LoadData(object sender, RoutedEventArgs e)
{
peopleList.Add(new people()
{
name = "小明",
age = "18",
sex = "男",
birthday = "1990-9-9"
});
peopleList.Add(new people()
{
name = "小红",
age = "18",
sex = "女",
birthday = "1990-9-9"
});
((this.FindName("DATA_GRID")) as DataGrid).ItemsSource = peopleList;
}