Add a checkbox for the DataGrid in WPF. Multiple options are supported.

Source: Internet
Author: User
The DataGrid is used in the project. You need to add the checkbox in the first column. You can select multiple or all. The concepts involved include ememplate, datagridcellstyle, datagridcellcontroltemplate, binding, and onpropertychanged. There are the following implementation ideas: 1. inherit the inotifypropertychanged interface and implement the onpropertychanged method: public abstract class viewmodelbase: inotifypropertychanged {public event propertychangedeventhandler propertychanged; // <summary> // raises this object & apos; s properchanged tyevent. /// </Summary> /// <Param name = "propertyname"> the property that has a new value </param> protected void onpropertychanged (string propertyname) {Property Changedeventhandler handler = propertychanged; If (null! = Handler) {handler (this, new propertychangedeventargs (propertyname ));}}//..................} 2. implement viewmodel, add the isselected attribute, and store the current multiple-choice status private bool _ isselected = true; Public bool isselected {get {return _ isselected;} set {_ isselected = value; onpropertychanged ("isselected") ;}} 3. after the VM/model is ready, we will start to customize the style of the DataGrid. 4. prepare the ememplate of the checkbox: <datatemplate X: Key = "checkboxdatatemplate1"> <Grid> <checkbox X: Name = "_ chkselected" Height = "16" horizontalalignment = "center" verticalalignment = "center" background = "{X: null} "verticalcontentalignment =" center "horizontalcontentalignment =" center "Click =" _ chkselected_onclick "isthreestate =" false "ischecked =" {binding isselected, mode = oneway, fallbackvalue = true} "/> </GRID> </datatemplate> in this example, the checkbox only has two simple states: 1) The ischecked attribute is bound to the isselected attribute of the VM; 2) the mode is Oneway is because you can select multiple rows and click a line header to select multiple rows. This function traverses all currently selected rows in the click event, and then changes the isselected attribute of its VM. Therefore, the twoway mode is not required; 3) the fallbackvalue is added to the binding, which indicates the default value given when the binding fails. In this example, because datatemplate is also applied to the column header, the datacontext of the column header is different from that of the datagridrow; 4) in the click event processing function, determine whether the column header currently clicked is still the row header, change the isselected attribute of the corresponding datacontext. For example, private void _ chkselected_onclick (Object sender, routedeventargs e) {checkbox chkselected = E. originalsource as checkbox; If (null = chkselected) {return;} var studymodel = chkselected. datacontext as studymodel; bool ischecked = chkselected. ischecked. hasvalue? Chkselected. ischecked. Value: true; frameworkelement templateparent = chkselected. templatedparent is frameworkelement? (Chkselected. templatedparent as frameworkelement). templatedparent as frameworkelement: NULL; If (templateparent is maid header) {mainviewmodel MVM = This. datacontext as mainviewmodel; If (null! = MVM) {foreach (VAR sm in MVM. studylist) {SM. isselected = ischecked ;}} else if (templateparent is datagridcell) {If (null! = Studymodel & null! = This. _ grdstudylist. selecteditems & this. _ grdstudylist. selecteditems. contains (studymodel) {foreach (VAR otherselected in this. _ grdstudylist. selecteditems. oftype <studymodel> () {otherselected. isselected = ischecked ;}}}mainviewmodel is the main Vm, which contains an observablecollection <studymodel> studylist, while studymodel contains the isselected attribute, both of which implement the properontychanged method; _ grdstudylist is the datagrid5. datatemplate is applied to the datagridcolumnheader and datagridcell, for example, <style X: Key = "datagridcheckboxcolumnheaderstyle1" targettype = "{X: type datagridcolumnheader} "> <setter property =" contenttemplate "value =" {dynamicresource checkboxdatatemplate1} "/> <setter property =" horizontalalignment "value =" stretch "/> <setter property = ""verticalignment" value = "stretch"/> </style> <style X: key = "maid" targettype = "{X: type datagridcell} "> <setter property =" padding "value =" 20, 0 "/> <setter property =" contenttemplate "value =" {dynamicresource checkboxdatatemplate1} "/> <setter property = "background" value = "# ffc1c1c1"/> <setter property = "borderbrush" value = "{X: null} "/> <setter property =" borderthickness "value =" 0 "/> <setter property =" template "value =" {dynamicresource datagridcheckboxcellcontroltemplate1} "/> <style. triggers> <trigger property = "isselected" value = "true"> <setter property = "background" value = "# ffc1c1"/> <setter property = "borderbrush" value =" {X: null} "/> </trigger> </style. triggers> </style> <controltemplate X: Key = "datagridcheckboxcellcontroltemplate1" targettype = "{X: Type datagridcell}"> <border
Borderbrush = "{templatebinding borderbrush }"
Borderthickness = "{templatebinding borderthickness }"
Background = "{templatebinding background }"
Snapstodevicepixels = "true"> <contentpresenter contenttemplate = "{templatebinding contenttemplate }"
Content = "{templatebinding content }"
Contentstringformat = "{templatebinding contentstringformat }"
Snapstodevicepixels = "{templatebinding snapstodevicepixels}"/> </Border> </controltemplate> 6. Apply cellstyle and headerstyle to the DataGrid:
<DataGrid
                x:Name="_grdStudyList"                 ItemsSource="{Binding StudyList}"                AutoGenerateColumns="False"                FrozenColumnCount="1" Background="#FF999797">            
          <DataGrid.Columns>                   
             <DataGridCheckBoxColumn 
                        x:Name="_dtcSelected"                        Header=""                         HeaderStyle="{StaticResource DataGridCheckboxColumnHeaderStyle1}"                         CellStyle="{StaticResource DataGridCheckboxCellStyle1}"                        MinWidth="60" CanUserReorder="False" MaxWidth="60"/>

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.