Change Silverlight 4 DataGrid Cell on Mouse Actions

I am using the Silverlight DataGrid from its first release and it’s an extremely useful control. However while programming the DataGrid for various UI as well as data binding operations, I still find it difficult to work with some basic DataGrid elements e.g. how to find a specific cell index in the DataGrid? I have come across this question during my training programs and I have discussed various ways to find out a specific cell when the user clicks on it. Last night (a sweet Saturday night), I decided to document a way to change the appearance of the Silverlight DataGridCell when the user moves the Mouse cursor over it. In this article, I am sharing the solution I came up with (there may be multiple ways possible.)

On a side note, check out these useful Silverlight DataGrid articles

Step 1: Open VS2010 and create a Silverlight application, name it as ‘SL4_DataGrid_Cell_Index’. In the MainPage.Xaml.cs, add the following classes as DataClasses.

silverlight datagrid

Step 2: Open MainPage.xaml and add the following XAML in it. The XAML contains DataGrid and also defines styles targeting the DataGridCell.

silverlight datagrid cell style

Step 3: If you carefully observe the XAML code, the LoadingRow event of the DataGrid is used. This event will be fired when the ItemsSource property of the DataGrid is set to some Collection and when the ItemsSource property will generate DataGridRow by creating an instance of it. Open MainPage.Xaml.cs and add the following code in the Loaded event:
image

Here I have also defined a support method ’GetElementParent’, which helps me in getting the Parent of a specific UI element. Typically I required this in the DataGrid because I cannot directly read the DataGridCell object, so first I need to retrieve the current row index and then get Cell contents using the Row object. To read the cell contents I have used the DataColumn object and its GetCellContent method. The code is as below:

silverlight datagrid loading row
Step 4: Run the application and move the mouse. The DataGridCell over which the mouse is hovered, will change its appearance as shown below:

silverlight datagrid mouse hover

Download the source code





About The Author

Mahesh Sabnis is a Microsoft MVP having over 18 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

No comments: