Using PreparingCellForEdit event in datagrid

PreparingCellForEdit event is useful when we want to customize/change the behaviour of the editing element based on some condition

lets say we have have 

 public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

and the following XAML

<data:DataGrid x:Name=”datagrid1″ ItemsSource=”{Binding}” AutoGenerateColumns=”False”>
            <data:DataGrid.Columns>
                <data:DataGridTextColumn Binding=”{Binding ID}” IsReadOnly=”True” />
                <data:DataGridTemplateColumn Header=”Name”
                                             >
                    <data:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text=”{Binding Name}”/>
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellTemplate>
                    <data:DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <TextBox  Text=”{Binding Name}” />
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellEditingTemplate>
                </data:DataGridTemplateColumn>
            </data:DataGrid.Columns>
        </data:DataGrid>
 for (int i = 0; i < 10; i++)
 persons.Add(new Person {ID=i, Name=”Person..”+ i.ToString() });

let’s say we want to disable editing of person whose id % 2 == 0

Here is what we can do

attach an event handler
 datagrid1.PreparingCellForEdit += new EventHandler<DataGridPreparingCellForEditEventArgs>(datagrid1_PreparingCellForEdit);
          
In the event handler, get the datacontext, check for our condition, if it matches and if the column is what we are interested in,  get the editing element (can be anything), in this case it is TextBox and set properties

 void datagrid1_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
        {           
            Person p = e.Row.DataContext as Person;
            if (p.ID % 2 == 0)
            {
                if (e.Column.DisplayIndex == 1)
                {
                    TextBox textBox = (e.EditingElement as TextBox);
                    textBox.IsReadOnly = true;
                    textBox.Background = new SolidColorBrush(Colors.Gray);                   
                }
            }
        }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s