【问题标题】:Update single cells in DataGrid更新 DataGrid 中的单个单元格
【发布时间】:2014-04-13 14:27:38
【问题描述】:

如何按行 ID 更新 DataGrid 中的单个单元格?

我的输出目前适用于一个静态行。 (MessageBox 输出显示正确的值) 我的意图是在整个 Grid 中使用它。

private void btnUpdateUserData_Click(object sender, RoutedEventArgs e)
{
   MessageBox.Show("ID: " + mUserDataObject[0].ID + ", Username: " + 
                    mUserDataObject[0].Username + ", Password: " + 
                    mUserDataObject[0].Password + ", Rolle: " + 
                    mUserDataObject[0].Role);
        // to be implemented
        // mUserDataObject[i].Username = "New Username";
}

XAML 代码

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Click="btnUpdateUserData_Click">Update</Button>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

【问题讨论】:

  • btnUpdateUserData_Click 处理程序挂在哪个按钮上。单独用于每一行还是在 DataGrid 的底部?
  • 我已经添加了上面的 XAML 代码。分别为每一行。
  • 我已经添加了一个答案。看看有没有帮助。

标签: c# wpf datagrid cell


【解决方案1】:

如果要更新单击按钮所在行的值,请获取按钮的 DataContext,它将代表 instance of User 对象。

直接为实例修改属性,如果 INotifyPropertyChanged 在 User 类上实现,它将立即反映在 UI 中。

private void btnUpdateUserData_Click(object sender, RoutedEventArgs e)
{
   dataGrid.CommitEdit(); // Add this line so that any editing cell gets commit.
   User currentUser = ((Button)sender).DataContext as User;    
   MessageBox.Show("ID: " + currentUser.ID + ", Username: " + 
                    currentUser.Username + ", Password: " + 
                    currentUser.Password + ", Role: " + 
                    currentUser.Role);   

   currentUser.Username = "New Username";
}

更新

如果要更新SelectedItem 的属性,请将x:Name 提供给您的dataGrid 并使用它来访问dataGrid 的选定项。

XAML

<DataGrid x:Name="dataGrid">
   ....
</DataGrid>

Code behind

private void btnUpdateUserData_Click(object sender, RoutedEventArgs e)
{
   dataGrid.CommitEdit(); // Add this line so that any editing cell gets commit.
   User currentUser = dataGrid.SelectedItem as User;
   // currentUser will be null in case SelectedItem is null.
   if(currentUser != null)
   {
      MessageBox.Show("ID: " + currentUser.ID + ", Username: " + 
                       currentUser.Username + ", Password: " + 
                       currentUser.Password + ", Rolle: " + 
                       currentUser.Role);

      currentUser.Username = "New Username";
   }
}

【讨论】:

  • 如果我想在 DataGrid 的底部进行更新,您有什么建议?
  • 在这种情况下获取 dataGrid SelectedItem 这将是用户实例。如果没有选择任何项目,它将返回 null。
  • 我也有另一种方法的更新答案。 @user3524628 - 取消选择答案的原因?
  • 很抱歉,但问题并没有完全解决:我总是得到旧的上下文数据,例如该行包含用户名“user”,我将其编辑为“user1234”并触发 btnUpdateUserData_Click( ) 我得到了“用户”。
  • 您需要在获取 DataContext 之前调用 dataGrid.CommitEdit(); 以便在您访问它之前提交任何处于编辑模式的单元格。 dataGrid 是 x:Name 您必须在 XAML 中的 DataGrid 上设置。我已经编辑了答案以包含详细信息。希望它对你有用。
猜你喜欢
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 2013-01-14
  • 1970-01-01
  • 2023-03-28
  • 2015-05-05
相关资源
最近更新 更多