Tuesday, September 01, 2009

Silverlight3 GridView Binding, LoadingRow events and Textblock traps

Those from ASP.NET background, moving forward to silverlight3 and playing around with Grid view my get frustrated at times. Grid view is one of the most widely used controls and we do want to change the contents of the Grid when we Bind the data. Sounds very simple but could be tricky at times.

I was developing prototype in Silverlight and Found few interesting things and thought I would share.

  1. So you bind the data to a grid, using AutoGenerate columns or not, Doesnt matter. To track the "GridView.RowDataBound" on row data bound event you create a backend event handler like this.
    grdEntries.LoadingRow += new EventHandler(grdEntries_LoadingRow);
  2. Getting event handler is tricky, here is how you get it working.  Note the 3 methods of getting the cell content in C# code. image

About this get parent function – this casts the cell to appropriate type – Note the way this function is called recursively.

The Above code may not work when you scroll the grid, for some wired reason it keeps binding the data again and again. For this, Alternative solution could be to use the individual column loaded even. Here is how you do it.

Both type of columns are shown here

<!--<data:DataGridTextColumn Binding="{Binding Date}" Header="Entry Date" Width="175"/>--> regular column which works with LoadingRow event handler

<data:DataGridTemplateColumn Header="Date" SortMemberPath="Date">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Loaded="TextBlock_Loaded" x:Name="txtDate" Text="{Binding Date}">
</TextBlock>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>

In the code behind, track the column and change the text or whatever you want to do.

void TextBlock_Loaded(object sender, EventArgs e)

     {

          TextBlock tb = sender as TextBlock;

          tb.Text = "Amol";

      }


Now why we have so many options? There are some performance reasons in data grid and it all depends which one to use whe. Typically, if you want to change data every time you bind grid, go with Loading row handler. If it static change and grid is not going to change then use the column loaded event.

Thanks

No comments: