Edit DataGrid Cell on mouse over

4.6k views Asked by At

I have a DataGrid which has plenty rows and columns, I want to get the cell ready for editing when the user focus the mouse on it (IsMouseOver).

So far, all I found is this

<Window.Resources>
    <Style TargetType="{x:Type DataGridCell}">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="green"></Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

I am able to set a property for the cell when the mouse is over it. But how to launch an event when the mouse is over?

2

There are 2 answers

0
Olaru Mircea On BEST ANSWER

I would add an EventSetter in a Style like this :

   <DataGrid.Resources>
         <Style TargetType="{x:Type DataGridCell}">
              <EventSetter Event="MouseEnter" Handler="EventSetter_OnHandler"/>
         </Style>
  </DataGrid.Resources>

Here is the handler:

    private void EventSetter_OnHandler(object sender, MouseEventArgs e)
    {
        DataGridCell dgc = sender as DataGridCell;

        TextBox tb = Utils.GetChildOfType<TextBox>(dgc);
        tb.Focus();
    }

In fact you said you want to edit something. In my case, there is a TextBox and i reach it with this helper:

     public static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
    {
        if (depObj == null) return null;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            var child = VisualTreeHelper.GetChild(depObj, i);

            var result = (child as T) ?? GetChildOfType<T>(child);
            if (result != null) return result;
        }
        return null;
    }

After reaching it, a simple Focus() will do the final job.

0
Dinesh balan On

You can launch a mouseover Event in Xaml Like this From where you have your DataGridCell

 <DataGridCell MouseEnter="DataGridCell_MouseEnter"/>