XamPivotGridでは、CellControlAttachedイベントを使うことで、セルの値に応じてセルの表示スタイル(背景色や文字色など)を動的に変更する条件付き書式を実装できます。

XamPivotGridの設定

条件に応じて切り替えるスタイルをWindow.ResourcesStyleとして定義し、XamPivotGridCellControlAttachedイベントにハンドラを割り当てます。

<Window.Resources>
    <Style x:Key="highValue" TargetType="ig:PivotCellControl">
        <Setter Property="Background" Value="LightCyan"/>
    </Style>
    <Style x:Key="negativeValue" TargetType="ig:PivotCellControl">
        <Setter Property="Foreground" Value="Red"/>
    </Style>
</Window.Resources>

<ig:XamPivotGrid x:Name="xamPivotGrid1" CellControlAttached="xamPivotGrid1_CellControlAttached" />

CellControlAttachedイベントの処理

ハンドラ内でセルの値を取得し、値がしきい値以下(赤字)またはしきい値以上(背景色変更)の場合に、対応するStylee.Cell.Styleへ設定します。最後にe.IsDirty = trueを設定することで、変更をセルの再描画に反映させます。

private void xamPivotGrid1_CellControlAttached(object sender, Infragistics.Controls.Grids.PivotCellControlAttachedEventArgs e)
{
    var rowIndex = this.xamPivotGrid1.DataRows.IndexOf(e.Cell.DataRow);
    var columnIndex = this.xamPivotGrid1.DataColumns.IndexOf(e.Cell.DataColumn);

    var cellData = this.xamPivotGrid1.DataSource.Result.Cells[rowIndex, columnIndex];

    if ((cellData != null) && (cellData.Value.ToString() != string.Empty))
    {
        var value = Double.Parse(cellData.Value.ToString()!);
        if (value <= 0)
        {
            e.Cell.Style = this.Resources["negativeValue"] as Style;
        }
        else if (value >= 10000000)
        {
            e.Cell.Style = this.Resources["highValue"] as Style;
        }

        e.IsDirty = true;
    }
}

実行結果

実行すると、売上額(SalesAmount)が0以下のセルは赤字、一定額以上のセルは背景色が水色で表示され、セルの値に応じてスタイルが切り替わっていることを確認できます。

Tagged:

製品について

Ultimate UI for WPF