Pavel Voronin
Pavel Voronin

Reputation: 13985

How to selectively disable editing in DataGrid?

By default editing is activated by F2, double click and typing in selected cell. How can I enable/disable these (some of them) editting triggers?

Upvotes: 2

Views: 1357

Answers (2)

denis morozov
denis morozov

Reputation: 6316

I think the cleanest way is to leave datagrid's behavior alone, it knows what it's doing, and create your own control in the edting template. Lets call it (for reference) CustomTextBox. Have that CustomTextBox do what you like, such as responding to F2 key only, etc. That way you are not creating weird behaviors in the datagrid, and encapsulating custom behaviors in your custom control.

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock DataContext="{Binding SomeProperty}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        <DataTemplate>
            <yourNamespace:CustomTextBox DataContext="{Binding SomeProperty}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn> 

Upvotes: 2

denis morozov
denis morozov

Reputation: 6316

datagrid.KeyDown += new KeyEventHandler(datagrid_KeyDown);

void datagrid_KeyDown(object sender, KeyEventArgs e)
    {
        //obviously you'll have to add some code here
        //if(!datagridIsInEditMode) then
            if (Keyboard.IsKeyDown(Key.F2))
                   datagrid.BeginEdit();
            else
                  e.Handled = true;
    }

Upvotes: 3

Related Questions