Wednesday, 28 March 2012

Adding Calculated Columns to WPF DataGrids

image

 

I’m still fairly new to DataBinding in WPF/XAML, and still in awe to degree of learning required to accomplish simple tasks such as Adding a calculated column to a DataGrid.

 

The most basic of solutions I found required a gross exaggeration of work that I’m not willing to undertake, especially for the simplicity of the task at hand.

 

So, in order to avoid having to write a unpleasant number of classes just to multiply one DataBound column with another, I’ve decided to make my DataContext a DataTable in a DataSet. With that, I’ve added a virtual column in the DataTable’s definition, and rather then defining a “Source” I alternatively defined an expression, which in turn is my intended calculation.

 

Column Expression’s are very flexible, so please review Microsoft’s Reference to see what it can do for you.

Advantages:

  1. No need to define attributes of the data within XAML, or resort to binding to static resources which you have to code.
  2. DataTables are easy to code, or if your as lazy as me, accessible through the DataSet Designer in Visual Studio. (The designer additionally gives you facility to test your expression by right clicking the table and selecting “Preview Data…”)
  3. Your XAML doesn’t need to bind to one column differently to than the others… In turn, allowing for AutoGenerateColumns as an available option.

Some XAML example

<DataGrid
    AutoGenerateColumns="False"
    ItemsSource="{Binding}"
    Name="DataGrid1">
    <DataGrid.Columns>
        <DataGridTextColumn 
            Header="Name"
            Binding="{Binding Path=Tenant_Name}" />
        <DataGridTextColumn 
            Header="Sq Feet&#x0d;&#x0a;"
            Binding="{Binding Path=Tenant_SqFeet}" />                
        <DataGridTextColumn 
            Header="Basic Rent&#x0d;&#x0a;"
            Binding="{Binding Path=Tenant_BaseRent}" />
        <DataGridTextColumn 
            Header="&#x0d;&#x0a;x Sq Feet"
            Binding="{Binding Path=Tenant_Calc_SqFeetByBaseRent}" />                
    </DataGrid.Columns>            
</DataGrid>

 

Now,

My only concern with this solution is that it’s too graceful not to be posted elsewhere. So if anyone can explain to me why this is not the ideal method for displaying a calculated column, please let me know in the comments.

 

Sincerely,

Twitter

Page Hits