Introduction
There is a more common requirement in a DataGrid-related project. That is, you can set the style of the row based on the data, such as the background color of the row or the color of the font. There are several ways we can use them, one for each.
Preparatory work
before introducing the method, define the data class, is a relatively simple score table, with name, score, etc., the code is as follows:
Public class score { publicstringgetset;} Public int Get Set ; } Public int Get Set ; } }
Then create an instance for the DataGrid assignment data source, as follows:
This. DataGrid. ItemsSource =Newlist<score> {NewScore {Name ="Little Red", Chinese = -, Math = the }, NewScore {Name ="Xiao Ming", Chinese = -, Math = - }, NewScore {Name ="Xiao Li", Chinese = the, Math = - }, NewScore {Name ="Ray", Chinese = -, Math = the}};
1. Data triggers
The simplest and easiest way to do this is to define a datatrigger, but the disadvantage is also obvious, only for a single data binding and to determine whether the data is equal. For example, we want to set the data background color of the language score equal to 90 to green, the code is as follows
<style > <Style.Triggers> <datatrigger binding="{Binding Chinese}" value="> <setter property="datagridrow.background " value="Green></Setter> </DataTrigger> </Style.Triggers></Style>
2. Value Converter
IValueConverter can only be applied to single data binding, but it is more powerful. For example, we want to set the data background color of the language score less than 60 to red, the code is as follows:
Define the Blackgroundconverter as follows:
Public classBlackgroundconverter:ivalueconverter { Public ObjectConvert (ObjectValue, Type TargetType,Objectparameter, CultureInfo culture) { if(int. Parse (value. ToString (), Numberstyles.any) < -) { return NewSolidColorBrush (colors.red); } Else { returnDependencyproperty.unsetvalue; } } Public ObjectConvertback (ObjectValue, Type TargetType,Objectparameter, CultureInfo culture) { returnDependencyproperty.unsetvalue; } }
Defining resources
<local:blackgroundconverter x:key="blackgroudconverter"></local: Blackgroundconverter>
Application Converters
<style > <setter property="datagridrow.background" value="{ Binding Chinese,converter={staticresource Blackgroudconverter}}"></setter></style >
In addition, there is a more powerful value converter imultivalueconverter, at the same time binding language and math scores, you can set the language score is greater than the mathematical results of the data to red, as follows:
Public classBlackgroudmulticonver:imultivalueconverter { Public ObjectConvert (Object[] values, Type targetType,Objectparameter, CultureInfo culture) { Try { intone =int. Parse (values[0]. ToString (), numberstyles.any); intboth =int. Parse (values[1]. ToString (), numberstyles.any); if(values[0] !=NULL&& values[1] !=NULL&& One >Both ) { return NewSolidColorBrush (colors.red); } Else { returnDependencyproperty.unsetvalue; } } Catch(Exception e) {returnDependencyproperty.unsetvalue; } } Public Object[] Convertback (ObjectValue, type[] targettypes,Objectparameter, CultureInfo culture) { return NULL; } }
3. Style Selector
Functionally, Styleselector is the top two. It can be used to determine multiple data values and apply settings for multiple properties. For example, we can set the data for the language score to be greater than the math score to red, the font color to blue, and the code as follows:
Public classDatagridstyleselector:styleselector { Public OverrideStyle Selectstyle (Objectitem, DependencyObject container) { if(item isscore) {Score TMP=(score) item; if(TMP. Chinese >tmp. Math) {returnstyle; } Else { return NULL; } } Else { return NULL; } } PublicStyle Style {Get;Set; } }
Defining resources
<local:datagridstyleselector x:key="Datagridstyleselector"> <local:DataGridStyleSelector.style> <Style> < Setter property="Datagridrow.background"Value="Red"></Setter> <setter property="Datagridrow.foreground"Value="Blue"></Setter> </Style> </local:datagridstyleselector.style></local: Datagridstyleselector>
Apply a style Selector
<datagrid name="DataGrid" autogeneratecolumns="False" rowstyleselector="{StaticResource datagridstyleselector}" >
However, the style selector also has a bad place, and when we dynamically edit the data, it does not automatically trigger the change of style. There is no elegant solution to this situation, and the corresponding style selector can be roughly set to null and set back when the data changes.
4. Random entry: Template selector
Datatemplateselector is also powerful, and it can completely change the way data is displayed. Unfortunately, the DataGrid has no rowtemplateselector. Only Celltemplateselector, We can use Celltemplateselector to make some interesting display of the cell, such as adding a little extra text description, as follows
Public classCelldatatemplateselector:datatemplateselector { Public OverrideDataTemplate Selecttemplate (Objectitem, DependencyObject container) { if(item isscore) {Score TMP=(score) item; if(TMP. Chinese >= -) { returntemplate1; } Else { returnTemplate2; } } Else { return NULL; } } PublicDataTemplate Template1 {Get;Set; } PublicDataTemplate Template2 {Get;Set; } }
Defining resources
<local:celldatatemplateselector x:key="Celldatatemplateselector"> <local:CellDataTemplateSelector.template1> <DataTemplate> <textblock foreground="Green"text="{Binding chinese,stringformat= good result: {0}}"></TextBlock> </DataTemplate> </local:celldatatemplateselector.templat E1> <local:CellDataTemplateSelector.template2> <DataTemplate> <textblock foreground="Red"text="{Binding chinese,stringformat= also effort: {0}}"></TextBlock> </DataTemplate> </local:celldatatemplateselector.templat E2></local:celldatatemplateselector>
Apply Template Selector
<datagridtemplatecolumn celltemplateselector="{StaticResource Celldatatemplateselector} " header= " Chinese score "> </DataGridTemplateColumn>
Again, it has the same drawbacks as the style selector.
Summary
This article from simple to complex introduction of data triggers, value converters, style selectors, template selectors, they have their own application scenarios, but also have their own limitations, in the use of attention. Finally, if you have better suggestions, please feel free!
The row style setting for the WPF DataGrid