如何按行ID更新DataGrid中的单个单元格?
我的输出目前适用于一个静态行。 (MessageBox输出显示正确的值) 我的目的是在整个网格中使用它。
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>
答案 0 :(得分:0)
如果您想要更新单击按钮的行的值,请获取代表 DataContext
对象的 instance of User
按钮。< / p>
直接为实例修改属性,只要 INotifyPropertyChanged
在用户类上实现,它就会立即反映在用户界面中。
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";
}
}