WPF 4 DataGrid Control (basic functions)

Source: Internet
Author: User

It is mentioned that DataGrid is frequently used in both web pages and application development. With it, we can flexibly display various data between rows and columns. This article describes the functions of DataGrid in WPF 4 in detail.

Custom Columns

By default, after the ItemSource attribute is set for the DataGrid Control, the DataGrid automatically generates columns based on the data type. The following table lists the four columns supported by the DataGrid and their data types.

You can useAutoGenerateColumnsAttribute Sets whether columns are automatically generated to add custom columns. If the DataGrid contains both "auto-generated columns" and "user-defined columns", create "user-defined columns" first ". The following code creates these four columns:

<Window x:Class="WPF4ControlTest.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:local="clr-namespace:WPF4ControlTest"        xmlns:assembly="clr-namespace:System;assembly=mscorlib"        Title="MainWindow" Height="200" Width="500">    <Window.Resources>        <ObjectDataProvider x:Key="sexEnum" MethodName="GetValues"                             ObjectType="{x:Type assembly:Enum}">            <ObjectDataProvider.MethodParameters>                <x:Type Type="local:SexOpt"/>            </ObjectDataProvider.MethodParameters>        </ObjectDataProvider>    </Window.Resources>    <Grid>        <DataGrid x:Name="dataGrid" ItemsSource="{Binding}" AutoGenerateColumns="False">            <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}"/>                <DataGridHyperlinkColumn Header="Email" Width="150"                                          Binding="{Binding Email}"/>            </DataGrid.Columns>        </DataGrid>    </Grid></Window>

Each column contains its own numerical type. in C #, create the Member class and SexOpt enumeration, and bind the memberData data to the DataGrid:

using System;using System.Windows;using System.Collections.ObjectModel;namespace WPF4ControlTest{    /// <summary>    /// Interaction logic for MainWindow.xaml    /// </summary>    public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            ObservableCollection<Member> memberData = new ObservableCollection<Member>();            memberData.Add(new Member()            {                Name = "Joe", Age = "23", Sex = SexOpt.Male,                Pass = true, Email = new Uri("mailto:Joe@school.com")            });            memberData.Add(new Member()            {                Name = "Mike", Age = "20",                Sex = SexOpt.Male, Pass = false,                Email = new Uri("mailto:Mike@school.com")            });            memberData.Add(new Member()            {                Name = "Lucy", Age = "25",                Sex = SexOpt.Female, Pass = true,                Email = new Uri("mailto:Lucy@school.com")            });            dataGrid.DataContext = memberData;        }    }    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 Uri Email { get; set; }    }}

In this way, you can create a DataGrid using custom columns:

Select Mode

By default, the DataGrid selection mode is "select all rows", and multiple rows can be selected at the same time (as shown in ).SelectionModeAndSelectionUnitAttribute to modify the selection mode of the DataGrid.

SelectionUnit: ContainsCell,FullRowAndCellOrRowHeaderThree unit selection modes.

· Cell: Select cells;

· FullRow: Select full row;

· CellOrRowHeader: You can select a cell or click the beginning of a row to select the entire row;

SelectionMode: dividedExtendedAndSingleTwo modes.

· Extended: Select multiple units (defined by SelectionUnit );

· Single: select a unique unit (defined by SelectionUnit );

<DataGrid x:Name="dataGrid" ItemsSource="{Binding}" AutoGenerateColumns="False"          SelectionUnit="Cell" SelectionMode="Extended">… …

Set the instance effect after SelectionUnit and SelectionMode:

Edit

By default, you can directly edit data in the DataGrid (The following table shows the relevant editing commands). Of course, you can also set the DataGrid to read-only through the IsReadOnly attribute.

<DataGrid x:Name="dataGrid" ItemsSource="{Binding}" AutoGenerateColumns="False"          SelectionUnit="Cell" SelectionMode="Extended" IsReadOnly="True">… …

Other settings

CanUserAddRows, CanUserDeleteRows, CanUserReorderColumns, CanUserResizeColumns,
CanUserResizeRows, CanUserSortColumns, FrozenColumnCount, and DisplayIndex

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.