WPF DataGrid 示例 应用源码
界面运行效果:
XMAL 源码:
<Window x:Class="WpfApp1.UI.DataGridExample"
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:WpfApp1.UI"
xmlns:assembly="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="DataGridExample" Height="782" Width="800">
<Window.Resources >
<ObjectDataProvider x:Key="sexEnum" MethodName="GetValues" ObjectType="{x:Type assembly:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type Type="local:SexOpt"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<!--设置日期列的显示方式-->
<DataTemplate x:Key="DateTemplate">
<StackPanel Width="40" Height="30">
<Border Background="Orange" BorderBrush="Black" BorderThickness="1">
<TextBlock Text="{Binding ExamDate,StringFormat={}{0:MM-dd}}" FontSize="10" HorizontalAlignment="Center"></TextBlock>
</Border>
</StackPanel>
</DataTemplate>
<!--设置日期列的编辑方式-->
<DataTemplate x:Key="EditingDateTemplate">
<DatePicker SelectedDate="{Binding ExamDate}"></DatePicker>
</DataTemplate>
<!--行模板 RowDetailsTemplate-->
<DataTemplate x:Key="RowDetails">
<Border BorderThickness="0" Background="Orchid" Padding="10">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Math:" VerticalAlignment="Center"></TextBlock>
<TextBlock Text="{Binding Math}" VerticalAlignment="Center" FontSize="15" FontWeight="Bold"></TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="History:" VerticalAlignment="Center" ></TextBlock>
<TextBlock Text="{Binding Histrory}" VerticalAlignment="Center" FontSize=" 15" FontWeight="Bold"></TextBlock>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
<Grid Margin="0,0,0,-111">
<Button x:Name="BtnToDataTable" Content="DataGridToDataTable" HorizontalAlignment="Left" Margin="394,690,0,0" VerticalAlignment="Top" Width="240" Height="39" Click="BtnToDataTable_Click"/>
<DataGrid x:Name="dataGrid" ItemsSource="{Binding}" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="95" Margin="0,17,0,0" VerticalAlignment="Top" Width="634">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="80" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Age" Width="50" Binding="{Binding Age}"/>
<DataGridComboBoxColumn Width="80" Header="Sex" SelectedItemBinding="{Binding Sex}"
ItemsSource="{Binding Source={StaticResource sexEnum}}" >
</DataGridComboBoxColumn>
<DataGridCheckBoxColumn Header="Pass Exam?" Width="100" Binding="{Binding Pass}">
</DataGridCheckBoxColumn>
<DataGridHyperlinkColumn Header="Email" Width="150" Binding="{Binding Email}">
</DataGridHyperlinkColumn>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="btnselectMode" Content="选择模式" HorizontalAlignment="Left" Margin="694,10,0,0" VerticalAlignment="Top" Width="75" Height="39" Click="BtnselectMode_Click"/>
<CheckBox x:Name="chkReadOnly" Content="只读" HorizontalAlignment="Left" Margin="725,64,0,0" VerticalAlignment="Top" Click="ChkReadOnly_Click"/>
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding}" AutoGenerateColumns="False"
SelectionUnit="CellOrRowHeader" IsReadOnly="True"
HorizontalAlignment="Left" Height="109" Margin="0,117,0,0" VerticalAlignment="Top" Width="634">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader" >
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="Yellow" Offset="0.5"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="13" />
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}">
<DataGridColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="SkyBlue" Offset="0.5"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="Width" Value="80"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="ToolTip" Value="Sort by Column"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGridColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Age" Binding="{Binding Age}">
<DataGridColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="LightGreen" Offset="0.5"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="Width" Value="50"/>
</Style>
</DataGridColumn.HeaderStyle>
</DataGridTextColumn>
<DataGridComboBoxColumn Header="Sex"
SelectedItemBinding="{Binding Sex}"
ItemsSource="{Binding Source={StaticResource sexEnum}}">
<DataGridColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="LightPink" Offset="0.5"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="Width" Value="70"/>
</Style>
</DataGridColumn.HeaderStyle>
</DataGridComboBoxColumn>
<DataGridCheckBoxColumn Header="Pass Exam?" Width="100"
Binding="{Binding Pass}"/>
<DataGridHyperlinkColumn Header="Email" Width="150"
Binding="{Binding Email}"/>
</DataGrid.Columns>
<DataGrid.RowHeaderStyle>
<Style TargetType="DataGridRowHeader">
<Setter Property="Content" Value=" ·¤"/>
<Setter Property="Width" Value="10"/>
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="SkyBlue" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="ToolTip" Value="Select this Row"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowHeaderStyle>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="SeaGreen"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
<Label Content="dataGrid" HorizontalAlignment="Left" Margin="650,64,0,0" VerticalAlignment="Top"/>
<Label Content="dataGrid1" HorizontalAlignment="Left" Margin="650,168,0,0" VerticalAlignment="Top"/>
<Label Content="dataGrid2" HorizontalAlignment="Left" Margin="650,297,0,0" VerticalAlignment="Top"/>
<DataGrid x:Name="dataGrid2" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="137" Margin="0,226,0,0" VerticalAlignment="Top" Width="634">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="80" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Age" Width="50" Binding="{Binding Age}"/>
<DataGridComboBoxColumn Width="80" Header="Sex" SelectedItemBinding="{Binding Sex}"
ItemsSource="{Binding Source={StaticResource sexEnum}}" >
</DataGridComboBoxColumn>
<DataGridCheckBoxColumn Header="Pass Exam?" Width="100" Binding="{Binding Pass}">
</DataGridCheckBoxColumn>
<DataGridTemplateColumn Header="Exam Date" CellTemplate="{StaticResource DateTemplate }" CellEditingTemplate="{StaticResource EditingDateTemplate }"></DataGridTemplateColumn>
<DataGridHyperlinkColumn Header="Email" Width="150" Binding="{Binding Email}">
</DataGridHyperlinkColumn>
</DataGrid.Columns>
</DataGrid>
<DataGrid x:Name="dataGrid3" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="137" Margin="0,365,0,0" VerticalAlignment="Top" Width="634"
AutoGenerateColumns="False" SelectionUnit="FullRow" RowDetailsTemplate="{StaticResource RowDetails}"
>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="80" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Age" Width="50" Binding="{Binding Age}"/>
<DataGridComboBoxColumn Width="80" Header="Sex" SelectedItemBinding="{Binding Sex}"
ItemsSource="{Binding Source={StaticResource sexEnum}}" />
<DataGridCheckBoxColumn Header="Pass Exam?" Width="100" Binding="{Binding Pass}"/>
<DataGridTemplateColumn Header="Exam Date" CellTemplate="{StaticResource DateTemplate}" CellEditingTemplate="{StaticResource EditingDateTemplate}"/>
<DataGridHyperlinkColumn Header="Email" Width="150" Binding="{Binding Email}"/>
</DataGrid.Columns>
</DataGrid>
<DataGrid x:Name="dataGrid4" ItemsSource="{Binding}" Margin="10,511,158,194">
</DataGrid>
<Label Content="dataGrid3" HorizontalAlignment="Left" Margin="650,424,0,0" VerticalAlignment="Top"/>
<Label Content="dataGrid4" HorizontalAlignment="Left" Margin="650,575,0,0" VerticalAlignment="Top"/>
</Grid>
</Window>
后台 C# 源码
using System;
using System.Windows;
using System.Data;
using System.Collections.ObjectModel;
namespace WpfApp1.UI
{
/// <summary>
/// DataGridExample.xaml 的交互逻辑
/// </summary>
public partial class DataGridExample : Window
{
public DataGridExample()
{
InitializeComponent();
ObservableCollection<Member> memberData = new ObservableCollection<Member>();
memberData.Add(new Member()
{
Name = "杨幂",
Age = "28",
Sex = SexOpt.Female,
ExamDate = new DateTime(2010, 4, 10),
Pass = true,
Math=80,
Histrory=100,
Email = new Uri("mailto:ym@qq.com")
});
memberData.Add(new Member()
{
Name = "阿华",
Age = "40",
Sex = SexOpt.Female,
ExamDate = new DateTime(2010, 4, 10),
Pass = true,
Math = 95,
Histrory = 98,
Email = new Uri("mailto:ah@qq.com")
});
memberData.Add(new Member()
{
Name = "刘德华",
Age = "55",
ExamDate = new DateTime(2010, 4, 10),
Sex = SexOpt.Male,
Pass = true,
Math = 100,
Histrory = 100,
Email = new Uri("mailto:dh@qq.com")
});
dataGrid.DataContext = memberData;
dataGrid1.DataContext = memberData;
dataGrid2.DataContext = memberData;
dataGrid3.DataContext = memberData;
}
private void BtnselectMode_Click(object sender, RoutedEventArgs e)
{
dataGrid.SelectionUnit = System.Windows.Controls.DataGridSelectionUnit.Cell;
dataGrid.SelectionMode = System.Windows.Controls.DataGridSelectionMode.Extended;
}
private void ChkReadOnly_Click(object sender, RoutedEventArgs e)
{
if (chkReadOnly.IsChecked == true)
{
dataGrid.IsReadOnly = true;
}
else
{
dataGrid.IsReadOnly = false;
}
}
private void BtnToDataTable_Click(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Columns.Add("Sex", typeof(string));
dt.Columns.Add("Pass",typeof(bool));
dt.Columns.Add("ExamDate", typeof(DateTime));
dt.Columns.Add("Email", typeof(string));
dt.Columns.Add("Math", typeof(int));
dt.Columns.Add("Histrory",typeof(int));
ObservableCollection<Member> OCMember = (ObservableCollection<Member>)dataGrid3.ItemsSource;
foreach(Member m in OCMember)
{
DataRow dr= dt.NewRow();
dr["Name"] = m.Name;
dr["Age"] = m.Age;
dr["Sex"] = m.Sex;
dr["Pass"] = m.Pass;
dr["ExamDate"] = m.ExamDate;
dr["Email"] = m.Email;
dr["Math"] = m.Math;
dr["Histrory"] = m.Histrory;
dt.Rows.Add(dr);
}
// dt = ((DataView)dataGrid3.ItemsSource).ToTable();
dataGrid4.ItemsSource = dt.DefaultView;
}
}
public enum SexOpt { Male,Female};
public class Member
{
public string Name { get; set; }
public string Age { get; set; }
public SexOpt Sex { get; set; }
public bool Pass { get; set; }
public DateTime ExamDate { get; set; }
public Uri Email
{
get; set;
}
public int Math { get; set; }
public int Histrory { get; set; }
}
}