Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGrid catch cell value changed event with a single click on UpdateSourceTrigger = SourceUpdated

I'm struggling to catch an event with a DataGrid. What I want to achieve is that when the user clicks ONCE on a checkbox of a datagrid cell, an event fires and I can get the current cell value. However the CellChangedEvent fires only when the selection changes, and the CellEditingEvent either fires when the cell loses focus, OR never fires. It never fires if I try to make a checkbox modificable with a single click, by doing the following:

<DataGrid Grid.ColumnSpan="2" Grid.Row="1" Grid.Column="0" AutoGenerateColumns="True" ItemsSource="{Binding MasterDataTable, Mode=TwoWay}" CanUserAddRows="False" Margin="10 5" CurrentCellChanged="DataGrid_CurrentCellChanged">
            <DataGrid.Resources>
                <Style TargetType="DataGridCell">
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="IsEditing" Value="True" />
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.Resources>
        </DataGrid>

How can I call a method as soon as the user clicks on a checkbox inside a cell? Thanks in advance.

like image 249
Filippo Vigani Avatar asked Nov 24 '13 11:11

Filippo Vigani


1 Answers

1) In your DataGrid register for TargetUpdated event .

2) Specify a Column , and ideally set AutoGenerateColumns=False .

3) In your Binding flag the NotifyOnTargetUpdated property (your target is your checkbox).

4) In your Binding UpdateSourceTrigger=PropertyChanged and Mode=TwoWay (not the default behavior of the DataGrid).

XAML :

 <DataGrid TargetUpdated="DataGrid_TargetUpdated" 
           AutoGenerateColumns="False" 
           ItemsSource="{Binding SomeValues, Mode=OneWay}"  CanUserAddRows="False"  >
    <DataGrid.Columns>
        <DataGridCheckBoxColumn Binding="{Binding Path=.,  NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Width="*"/>                        
    </DataGrid.Columns>
</DataGrid>

in CS: (where you might wan't to handle that event.)

   private void DataGrid_TargetUpdated(object sender, DataTransferEventArgs e)
   {
         // Do what ever...
   }  
like image 144
eran otzap Avatar answered Oct 27 '22 14:10

eran otzap