Search code examples
c#wpfwpfdatagrid

Is it possible to have user entered data on a WPF data grid be stored to a string var?


I have a data grind in WPF that is filled by a class. I have a button that in each row. I'm trying to make it so that when the button is clicked after an edit, the boxes in the row will convert there contents to string var. The var will be used to pass the changed info to a function.

.xaml

<DataGrid x:Name = "NAME"  ItemsSource = "{Binding}" AlternatingRowBackground="DarkGray" AlternationCount="2" HorizontalAlignment = "Stretch" VerticalAlignment = "Top" AutoGenerateColumns = "False" >
    <DataGrid.Columns>
        <DataGridTextColumn Binding = "{Binding PreferenceExtCode}" Header = "Name"  />
        <DataGridTextColumn Binding = "{Binding CustPrefValue}" Header = "Value" />
        <DataGridTemplateColumn Header="View">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Name="BtnSave" Content="SAVE" Click="BtnSave_Click"  />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

.cs

private void BtnSave_Click(object sender, RoutedEventArgs e)
{
    UpdatePref gridRow = (UpdatePreference)((Button)e.OriginalSource).DataContext;

    UpdatePref updatePref = (UpdatePref )((Button)e.Source).DataContext;
    string Name = updatePref.PreferenceExtCode;
    string Value = updatePref.CustPrefValue;
    // ...
}

I want the button click to save the edited values rather than the original ones.


Solution

  • You could set the UpdateSourceTrigger of the bindings to PropertyChanged:

    <DataGridTextColumn Binding="{Binding PreferenceExtCode, UpdateSourceTrigger=PropertyChanged}" Header="Name"  />
    <DataGridTextColumn Binding="{Binding CustPrefValue, UpdateSourceTrigger=PropertyChanged}" Header="Value" />