A common requirement for a DataGrid is to have entire rows that are read-only. You may have a list of records in your DataGrid and some need to be locked for various reasons. Unfortunately, in the XAML definition of a DataGrid, there isn’t a way to mark a row as being Read-Only. To accomplish this without tying my view to my model or rewriting the DataGrid, I’m utilizing the BeginningEdit event, the Tag property of the DataGridRow, and created a style for the DataGridRow with a DataTrigger to put everything together.
First thing I did was to make sure my Model had an IsReadOnly property to latch onto, in the attached sample code, I did this by adding the property to one of the Customer in the Northwind database .
Next, using a Trigger in my DataGridRow style, if the data item’s IsReadOnly property evaluates to “True” then I set the DataGridRow ‘s Tag to a string I can look for in my BeginningEdit event handler. In the sample project attached and in the code snippets below, I used the string “ReadOnly”. For a visual cue, I also set the HeaderTemplate to show an image to indicate that the row is locked.
- <!– Row Header Template to show a Locked icon.–>
- <DataTemplate x:Key="rowHeaderTemplate">
- <StackPanel Orientation="Horizontal">
- <Image x:Name="editImage" Source="Images/lock.gif" Width="16" Margin="1,0" />
- </StackPanel>
- </DataTemplate>
- <!– DataGridRow Style –>
- <Style x:Key="ReadOnlyCheck" TargetType="{x:Type DataGridRow}">
- <Style.Triggers>
- <DataTrigger Binding="{Binding IsReadOnly}" Value="True">
- <Setter Property="Tag" Value="ReadOnly" />
- <Setter Property="HeaderTemplate" Value="{StaticResource rowHeaderTemplate}">
- </Setter>
- </DataTrigger>
- </Style.Triggers>
- </Style>
Finally, in my BeginningEdit event handler for my DataGrid, I look at the Row going into Edit Mode, if its Tag property has been set to “ReadOnly” I cancel the event so it never makes it into edit mode. This enforces the IsReadOnly property from my mode.
- /// <summary>
- /// Event Handler for BeginningEdit Event of DataGrid. If the Row entering into Edit Mode has a Tag set to "ReadOnly",
- /// cancel the edit.
- /// </summary>
- /// <param name="sender">Reference to the DataGrid</param>
- /// <param name="e">Instance of DataGridBeginningEditEventArgs</param>
- private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
- {
- if (((DataGridRow)e.Row).Tag != null && ((DataGridRow)e.Row).Tag.ToString() == "ReadOnly")
- {
- e.Cancel = true;
- }
- }
by
Pingback: Windows Client Developer Roundup 076 for 7/25/2011 - Pete Brown's 10rem.net
Nice! Exactly what I looked for!
Not many examples on the net for this.
I found something similar on http://clear-code.blogspot.com/2012/03/wpf-datagrid-edit-row-toggle-button.html
Pingback: #çalışma notları 01:düzenlenebilir list,datagrid istenen satırın düzenlenmesi istenmeyenin engellenmesi | Mis Gibi..
Thank you, buddy! Very usefull stuff