WPF DataGrid common Property records

Source: Internet
Author: User
Tags xpath wpf datagrid

WPF DataGrid common Property records


Common Methods for components:

BeginEdit: Causes the DataGrid to enter edit state.

CancelEdit: Cancels the edit state of the DataGrid.

Collapserowgroup: The row grouping that closes the DataGrid.

commitedit: Verify that the DataGrid's edits are complete.

expandrowgroup: Expands the row grouping for the DataGrid.

Getgroupfromitem: Gets grouped from the specific item.

scrollIntoView: Scrolls the DataGrid view.

Component Common Properties:

alternatingrowbackground: Gets or sets a brush used to depict the background of an odd row of DataGrid.

Arerowdetailsfrozen: Gets or sets a value that determines whether to freeze the details of each line of content.

Arerowgroupheadersfrozen: Gets or sets a value used to determine whether to freeze the head of a grouped row.

AutoGenerateColumns: Gets or sets a value that determines whether table columns are allowed to be automatically generated.

canuserreordercolumns: Gets or sets a value that determines whether the user is allowed to rearrange the table column position.

canusersortcolumns: Gets or sets a value that is used to determine whether the user is allowed to sort the contents of a table by column.

CellStyle: Gets or sets the style of the cell.

columnheaderheight: Gets or sets the height of the column header.

ColumnHeaderStyle: Gets or sets the style of the column header.

Columns: Gets the collection that contains all the columns in the component.

ColumnWidth: Gets or sets the column width.

currentcolumn: Gets or sets the column that contains the current cell.

CurrentItem: Gets the data item that contains the current cell and is bound to the row.

Dragindicatorstyle: Gets or sets the style when the column header is dragged.

Droplocationindicatorstyle: Gets or sets the style when the column header is rendered.

Frozencolumncount: Gets or sets the number of frozen columns.

gridlinesvisibility: Gets or sets the display form of the grid lines.

headersvisibility: Gets or sets the display of the Wardrobe and column headers.

Horizontalgridlinesbrush: Gets or sets the brush for the horizontal grid line.

horizontalscrollbarvisibility: Gets or sets the display style of the horizontal scroll bar.

isreadonly: Gets or sets whether the DataGrid is read-only.

maxcolumnwidth: Gets or sets the maximum column width of the DataGrid.

mincolumnwidth: Gets or sets the minimum column width of the DataGrid.

rowbackground: Gets or sets the brush used to populate the row background.

rowdetailstemplate: Gets or sets the template that is used to display the contents of the detail section of the row.

Rowdetailsvisibilitymode: Gets or sets a value that determines whether the row detail section is displayed.

rowgroupheaderstyles: Gets the style that renders the row group header.

Rowheaderstyle: Gets or sets the style of the current header.

rowheaderwidth: Gets or sets the width of the wardrobe.

RowHeight: Gets or sets the height of each row.

RowStyle: Gets or sets the style that appears when it is present.

SelectedIndex: Gets or sets the index value of the currently selected part.

SelectedItem: Gets or sets the data item that is bound to the currently selected row.

SelectedItems: Gets a list of data items that are bound to the currently selected rows.

SelectionMode: Gets or sets the selection mode of the DataGrid.

Verticalgridlinesbrush: Gets or sets the brush for the vertical grid line.

verticalscrollbarvisibility: Gets or sets the display style of the vertical scroll bar.

Component Common events:

Beginningedit: Occurs before a cell or row enters edit mode.

celleditended: Occurs when a cell edit has been confirmed or canceled.

celleditending: Occurs when a cell is ending editing.

currentcellchanged: Occurs when a cell becomes the current cell.

Preparingcellforedit: Occurs when a cell under Datagridtemplatecolumn enters edit mode.

selectionchanged: Occurs when the SelectedItem or SelectedItems property value changes.

1.DataGrid Interlaced Color

Rowbackground and Alternatingrowbackground set the background for a row of alternating rows. Alternationcount is the total number of styles or colors that will be used for the row

1 <datagrid name= "DG" Rowheaderwidth= "alternationcount=" 2 "alternatingrowbackground=" #F4F4F4 "  autogeneratecolumns= "False" grid.row= "1" headersvisibility= "All"  margin= "4" >2                     <datagrid.columns >3                         <datagridtextcolumn binding= "{Binding Name}" header= "name"/>4                     </datagrid.columns>5                 </DataGrid>

If the Alternatingrowbackground brush is set, it will be assigned to the line, where (rownumber%alternationidex) = = 1

1 <style x:key= "Datagriddemorowstyle"   2 targettype= "{x:type Custom:datagridrow}" > 3 <Style.Triggers> 4 <trigger property= "Alternationindex" value= "2" > 5  <setter property= "Background" value= "{ StaticResource Rowbackgroundalternationindex2brush} "/> 6 </Trigger> 7 <trigger property=" Alternationindex "value=" 3 "> 8 <setter property=" Background "value=" {StaticResource Rowbackgroundalternationindex3brush} "/> 9 </trigger>10 </style.triggers>11 </Style>

Note For the above style, purposeful, I only cover alternationindex= 2, 3. For alternationindex= 0 o'clock, it uses rowbackground.
For alternationindex= 1, it uses alternatingrowbackground from the DataGrid.

The Errortemplate property of 2.DataGrid

1 <style x:key= "{x:type DataGridRow}" targettype= "{x:type DataGridRow}" > 2         <setter property= "Background" Value= "Transparent"/> 3         <setter property= "Snapstodevicepixels" value= "true"/> 4         <setter Property= "Validation.errortemplate" value= "{x:null}"/> 5         <setter property= "Validationerrortemplate" > 6             <Setter.Value> 7                 <ControlTemplate> 8                     <textblock margin= "2,0,0,0" verticalalignment= " Center "foreground=" #FFdc000c "text="! "/> 9                 </controltemplate>10             </setter.value>11         </setter>12 </Style>

The above XAML sets the DataGridRow validationerrortemplate for rowheader through the template

 1 <style x:key= "{x:type Datagridrowheader}" targettype= "{x:type Datagridrowheader}" > 2 <setter Property= "Background" value= "{DynamicResource datagridheaderbackground}"/> 3 <setter property= "Foreground" value= "{D Ynamicresource datagridheaderforeground} "/> 4 <setter property=" BorderBrush "value=" {DynamicResource DataGr Idgridlines} "/> 5 <setter property=" borderthickness "value=" 0,0,0,1 "/> 6 <setter Property=" W Idth "value="/> 7 <setter property= "Template" > 8 <Setter.Value> 9 &L T ControlTemplate targettype= "{x:type Datagridrowheader}" >10 <grid>11 & Lt Border background= "{TemplateBinding Background}" borderbrush= "{TemplateBinding Borderbru                                 SH} "borderthickness=" {TemplateBinding borderthickness} "14 Padding = "{TemplAtebinding Padding} ">15 <stackpanel orientation=" Horizontal ">17 <contentpresenter snapstodevicepixels= "{TemplateBinding snapstodevicepixels}" verticalalignment= "Center"/                                          >18 <control snapstodevicepixels= "false" 19 Visibility= "{Binding relativesource={relativesource ancestortype={x:type DataGridRow}}, Path= (Validation.HasError) , Converter={staticresource Booleantovisibilityconverter}} "template=" {Binding                             Relativesource={relativesource Ancestortype={x:type DataGridRow}}, path=validationerrortemplate} "/>21 </stackpanel>22 </border>23 <thumb x:name= "part _topheadergripper "verticalalignment=" Top "style=" {Stati Cresource Rowheadergripperstyle}"/>26 <thumb x:name=" Part_bottomheadergripper "Verticalalig                     Nment= "Bottom" style= "{StaticResource Rowheadergripperstyle}"/>29 </grid>30 </controltemplate>31 </setter.value>32 </setter>33 3 4 <style.triggers>35 <trigger property= "IsMouseOver" value= "True" >36 <s Etter property= "Background" value= "{DynamicResource datagridheaderbackgroundhover}"/>37 <setter Pro             Perty= "Foreground" value= "{DynamicResource datagridheaderforegroundhover}"/>38 </trigger>39 <trigger property= "ispressed" value= "True" >40 <setter property= "Background" value= "{Dynamicre SOURCE datagridheaderbackgroundpressed} "/>41 <setter property=" Foreground "value=" {DynamicResource DatagridheaderforegroundPressed} "/>42 </trigger>43 <trigger property=" isrowselected "value=" True ">44                 <setter property= "Background" value= "{DynamicResource datagridheaderbackgroundselected}"/>45 <setter property= "Foreground" value= "{DynamicResource datagridheaderforegroundselected}"/>46 </ trigger>47 </style.triggers>48 </Style>

Master for error verification is mainly when there is an error control display, and get the above set datagridrow Error validation template control template, when there is no error, hide the control as the validation display

3.DataGrid View (sort, filter, group)

CollectionView Introduction

In fact, when you bind a background data list to a list control, WPF adds a layer called CollectionView (List view) between the data list and the list control silently, and it supports many advanced operations, such as sorting, grouping, Filter etc. so that we can divide the process into 3 parts: the data list (which maintains the background data), the list view (which maintains some additional states, such as "Current item", "sort", etc.), and the list control (which is responsible for rendering the CollectionView, not the collection)

1 CollectionView CV = new CollectionView (myList); 2 3 This.listBox.ItemsSource = CV;

CollectionViewSource Introduction

CollectionViewSource is a XAML proxy for CollectionView, meaning that CollectionView cannot be used in XAML, and if you want to bind CollectionView to a list control in XML, then please use CollectionViewSource. Its basic relationship with CollectionView is "has A". CollectionViewSource has a view property of type CollectionView to specify its corresponding CollectionView object, corresponding to it, and a source property to indicate the source of the data. A simple process is: Bind the data list to the Source property of the CollectionViewSource, The ItemsSource property of the list control is then bound to the View property of CollectionViewSource. Why don't you just bind the list control's Itemsource property to the data list? It depends on whether you need to find the CollectionViewSource and then find the view to perform the views (such as sorting, navigating, etc.). This may be a bit confusing. Take a look at the following example:

 1 <Window.Resources> 2 3 <xmldataprovider x:key= "Employees" xpath= "/employees/*" > 4 &L T;x:xdata> 5 <employees xmlns= "" > 6 <employee name= "Terry Adams" type= "F TE "employeenumber=" 1 "/> 7 <employee name=" Claire O&apos;donnell "type=" FTE "Employeenumbe                      R= "12345"/> 8 <employee name= "Palle Peterson" type= "FTE" employeenumber= "5678"/> 9 <employee name= "Amy E. Alberts" Type= "CSG" employeenumber= "99222"/>10 <employ EE name= "Stefan Hesse" type= "Vendor" employeenumber= "-"/>11 </employees>12 </x: xdata>13 </xmldataprovider>14 <datatemplate datatype= "Employee" >16 <t Extblock text= "{Binding [email protected]}"/>17 </datatemplate>18 </window.res Ources>20 < Stackpanel>22 <listbox itemssource= "{Binding source={staticresource Employees}}"/>23 </stackpane L>

In the example above, we used the traditional way to bind the ListBox's ItemsSource to a xmldataprovider and worked well, and later we found that WPF could use CollectionView to sort the list, Of course this sort we want to just be in the presentation layer, so we decided to do it in XAML. When we actually revamp this code, we break our brains, because it's not easy to find CollectionView objects in XAML for our data.

In fact, we just need to change the process of data binding. We associate the data with the CollectionViewSource and then collectionviewsource the list control. Then we can insert any sort of order we want in CollectionViewSource.

 1 <Window.Resources> 2 3 <xmldataprovider x:key= "Employees" xpath= "/employees/*" > 4 &L T;x:xdata> 5 <employees xmlns= "" > 6 <employee name= "Terry Adams" type= "F TE "employeenumber=" 1 "/> 7 <employee name=" Claire O&apos;donnell "type=" FTE "Employeenumbe                      R= "12345"/> 8 <employee name= "Palle Peterson" type= "FTE" employeenumber= "5678"/> 9 <employee name= "Amy E. Alberts" Type= "CSG" employeenumber= "99222"/>10 <employ EE name= "Stefan Hesse" type= "Vendor" employeenumber= "-"/>11 </employees>12 </x: xdata>13 </xmldataprovider>14 <collectionviewsource x:key= "CVS" source= "{Bindin G Source={staticresource Employees}, xpath=/employees/*} ">16 <CollectionViewSource.SortDescriptions> <!--Insert the sort description here-->18 </collectionviewsource.sortdescriptions>19 <collectionviewsource.gr Oupdescriptions>20 <!--Insert a group description here-->21 &LT;/COLLECTIONVIEWSOURCE.GROUPDESCRIPTIONS&G              t;22 </collectionviewsource>23 <datatemplate datatype= "Employee" >25 <textblock text= "{Binding [email protected]}"/>26 </datatemplate>27 Dow. resources>29 <stackpanel>31 <listbox itemssource= "{Binding source={staticresource cvs}}" X:Na Me= "LB"/>32 </StackPanel>

The default DataSet view is for reference:

Collection data Default view Comments

IEnumerable

CollectionView

Items cannot be grouped.

IList

Listcollectionview

The quickest.

IBindingList

Bindinglistcollectionview

public partial class Window1:window    {        private void Buttonprevious_click (object sender, RoutedEventArgs e)        {            Icollectionview view = Getfamilyview ();            View. Movecurrenttoprevious ();        }        private void Buttonnext_click (object sender, RoutedEventArgs e)        {            Icollectionview view = Getfamilyview ();            View. Movecurrenttonext ();        }        Icollectionview Getfamilyview ()        {            people people = this. FindResource ("Family") as people;            Return Collectionviewsource.getdefaultview (people);        }    }

    • Filter filter

Also provide click events for the Sort button as follows:

1 private void Buttonfilter_click (object sender, RoutedEventArgs e) 2         {3             Icollectionview view = Getfamilyview (); 4             view. Filter = Delegate (object target) 5                 {6                     return (person) target). Age > 25; 7                 }; 8             //view. Filter = new Predicate<object> (delegate (object target) 9             //    {ten             //        return (person) target. Age > 25;11             //    });         

Filter is relatively simple, not repeat. In this case, just understand the predicate<object> type, this delegate variable filter is OK. Every item in the view that satisfies the criteria is returned.

    • Group

To get the data source view, in the grouping description, add the attribute grouping description that needs to be grouped,

1 private void Buttongroup_click (object sender, RoutedEventArgs e) 2         {3             Icollectionview view = Getfamilyview () ; 4             view. Groupdescriptions.add (New Propertygroupdescription ("Age")); 5         }

The next step is to turn on the Groupstyle and set the Groupstyle style.

Note: The name that is bound in Groupstyle does not refer to the name in person, but to the view. Groupdescriptions.add (New Propertygroupdescription ("Age"));

As mentioned above, this is one of the simplest groupings, in practical applications, the groupings tend to be more complex. For example, in terms of age group, it is impossible to do as a group of one year old as above. Now, let's implement the following grouping requirements:

0-30: Young;

30-60: Middle age;

>60: old age;

All custom groupings need to implement interface IValueConverter, as follows:

1 class Agetorangeconver:ivalueconverter 2     {3  4         #region IValueConverter member 5  6 Public         Object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 7         {8             int Ivalue = (int) value; 9             if (0 < ivalue && ivalue <=) {One                 return "young";             }13             else if (ivalue &am p;& ivalue <=) ("                 middle Age",             }17             else18             {                 return "old age";             }21         }22-Public         Object Convertback (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)             (new NotImplementedException ();         }27         #endregion29     }

Then, click the event to change to:

1 private void Buttongroup_click (object sender, RoutedEventArgs e) 2         {3             Icollectionview view = Getfamilyview (); 4             view. Groupdescriptions.add (New Propertygroupdescription ("Age", New Agetorangeconver ())); 5         }

As you can see, the groupings have been implemented according to our requirements.

    • Sort

Basic implementation Sequencing

1 private void Buttonsort_click (object sender, RoutedEventArgs e) 2         {3             Icollectionview view = Getfamilyview (); 4< C7/>view. Sortdescriptions.add (New Sortdescription ("Age", listsortdirection.ascending)); 5         }

Sometimes the default comparer does not meet the needs of our sorting, we use a custom sort

1 class Personagesort:icomparer 2     {3  4         #region IComparer member 5  6 Public         int Compare (object x, Object Y) 7         {8 person             PersonX = x as person, 9 person             persony = y as person;10             if (PersonX. Age > PersonY. Age)             {                 1;13             }14             else if (PersonX). Age = = PersonY. Age)             {                 0;17             }18             else19             {                 return-1;21             }22             //return PersonX. Age.compareto (PersonY. age);         }24         #endregion26     }27      Then, the button event is changed to: $         private void Buttonsort_click (object sender, RoutedEventArgs e)-         {             Listcollectionview view = Getfamilyview () as listcollectionview;33             View. Customsort = new Personagesort ();                        *         

Note in the button event, we transform the Getfamilyview method return value to Listcollectionview. Because he was in WPF, the class used to wrap the IList interface and provide view functionality. There are also implementations of Icollectionview interfaces in WPF, but some do not provide custom sorting, so be aware of them in use. Especially

WPF DataGrid common Property records

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.