Search code examples
wpfbindingdatagrid

wpf binding issue with ItemsSource


<ItemsControl ItemsSource="{Binding DataViews}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <DataGrid MaxHeight="500" VerticalScrollBarVisibility="Auto" VerticalAlignment="Stretch" Margin="0,0,10,0" MaxColumnWidth="450"
                                          RowStyle="{StaticResource DataGridRowSql}" Style="{StaticResource DataGridStyleSQL}"
                                          ColumnHeaderStyle="{StaticResource StyleDataGridColumnHeaderDefault}" ItemsSource="{Binding}"
                                          IsReadOnly="{Binding RelativeSource={RelativeSource AncestorType=Page},Path=Locked}"
                                          RowEditEnding="DataGrid_RowEditEnding" >
                                    <DataGrid.CommandBindings>
                                        <CommandBinding Command="Copy" Executed="CommandBinding_Executed"></CommandBinding>
                                    </DataGrid.CommandBindings>
                                    <DataGrid.InputBindings>
                                        <KeyBinding Key="C" Modifiers="Ctrl" Command="Copy"></KeyBinding>
                                    </DataGrid.InputBindings>
                                </DataGrid>
                                <GridSplitter Background="Red" Height="10" HorizontalAlignment="Stretch" ResizeDirection="Rows" ResizeBehavior="PreviousAndNext"></GridSplitter>
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel VerticalAlignment="Stretch"></StackPanel>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>

hi, I need to have the updated data in the DataGrid_RowEditEnding event, since the e.Row doesn't have the updated data, so I thought about adding <ItemsControl ItemsSource = "{Binding DataViews, Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}" > but it doesn't work, where am I wrong?


Solution

  • You will get the updated value in the CellEditEnding event handler if you just set the UpdateSourceTrigger property of the bindings to PropertyChanged.

    If you are using auto-generated columns, you could handle the AutoGeneratingColumn for the DataGrid to do this:

    private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        DataGridBoundColumn dataGridBoundColumn = e.Column as DataGridBoundColumn;
        if (dataGridBoundColumn != null)
        {
            dataGridBoundColumn.Binding = new Binding(e.PropertyName) { UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
        }
    }