How to: Apply Conditional Formatting in Code-Behind
- 2 minutes to read
This example demonstrates how to change the appearance of individual cells based on specific conditions using the Conditional Formatting feature in code-behind.
The image below shows the result.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ConditionalFormatting"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid" x:Class="ConditionalFormatting.MainWindow"
Title="MainWindow" Height="500" Width="800">
<Window.DataContext>
<local:ConditionalFormattingViewModel/>
</Window.DataContext>
<Grid>
<dxg:GridControl Name="grid" ItemsSource="{Binding Path=Items}" AllowLiveDataShaping="True" EnableSmartColumnsGeneration="True">
<dxg:GridControl.Columns>
<dxg:GridColumn FieldName="State" IsSmart="True" SortIndex="0" VisibleIndex="0"/>
<dxg:GridColumn FieldName="Sales" IsSmart="True" VisibleIndex="1"/>
<dxg:GridColumn FieldName="SalesVsTarget" IsSmart="True" FixedWidth="True" VisibleIndex="2"/>
<dxg:GridColumn FieldName="Profit" IsSmart="True" VisibleIndex="3"/>
<dxg:GridColumn FieldName="CustomersSatisfaction" IsSmart="True" FixedWidth="True" VisibleIndex="4"/>
<dxg:GridColumn FieldName="MarketShare" IsSmart="True" FixedWidth="True" VisibleIndex="5"/>
</dxg:GridControl.Columns>
<dxg:GridControl.View>
<dxg:TableView AllowEditing="False" AllowConditionalFormattingMenu="True" Name="view"/>
</dxg:GridControl.View>
</dxg:GridControl>
</Grid>
</Window>
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Core.ConditionalFormatting;
using System.Windows;
using System.Windows.Media;
namespace ConditionalFormatting {
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
view.FormatConditions.AddRange(new List<FormatConditionBase> {
new FormatCondition() {
Expression = "[SalesVsTarget] < 0.0m",
FieldName = "SalesVsTarget",
PredefinedFormatName = "RedText"
},
new FormatCondition() {
Expression = "[Profit] < 0.0",
FieldName = "Profit",
Format = new Format() {
Foreground = Brushes.Red
}
},
new DataBarFormatCondition() {
FieldName = "Sales",
PredefinedFormatName = "RedGradientDataBar"
},
new TopBottomRuleFormatCondition() {
Expression = "[Sales]",
FieldName = null,
PredefinedFormatName = "BoldText",
Rule = TopBottomRule.TopPercent,
Threshold = 10d
},
new DataBarFormatCondition() {
FieldName = "Profit",
PredefinedFormatName = "GreenGradientDataBar"
},
new IconSetFormatCondition() {
FieldName = "MarketShare",
PredefinedFormatName = "Quarters5IconSet"
}
});
}
}
}