是否可以将用户在 WPF 数据网格上输入的数据存储到字符串变量中?

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

我在 WPF 中有一个数据研磨,由 class 填充。我在每一行都有一个按钮。我试图做到这一点,以便在编辑后单击按钮时,行中的框会将那里的内容转换为字符串 var。 var 将用于将更改的信息传递给函数。

.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;
    // ...
}

我希望单击按钮来保存编辑后的值而不是原始值。

您可以将绑定的 UpdateSourceTrigger 设置为 PropertyChanged:

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