WPF中修改DataGrid单元格值并保存

编辑DataGrid中的单元格的内容然后保存是非常常用的功能。主要涉及到的方法就是DataGrid的CellEditEnding  和BeginningEdit 。其中BeginningEdit 是当单元格选中后,状态为可编辑状态时触发。CellEditEnding 是在单元格失去焦点后触发的事件。    对于编辑DataGrid中单元格内容的实现逻辑比较简单:

1.保存旧的单元格内容。
2.判断修改后的内容是否符合规范。
3.保存到数据库。
以下就是简单的实现逻辑,仅供参考:
前台代码:


<DataGrid Grid.Row="1" x:Name="dgData"
CellEditEnding="CellEditEnding"
BeginningEdit="BeginningEdit">
<!--需要完善,除了序号,基本完善-->
<DataGrid.Columns>

<DataGridTemplateColumn Header=" 序号" Width="50" MinWidth="10" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,0,0,0"></TextBlock>

</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

<DataGridTextColumn Binding="{Binding Name}" Width="*" Header="账套名称" IsReadOnly="False"/>

</DataGrid.Columns>
</DataGrid>

后台代码:

private void CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{


string newValue = (e.EditingElement as TextBox).Text;

//判断新名称和就名称是否一样
if (ZTName!=newValue)
{


DataAccess.IAccountDAL iaccount = DALResolver.Instance.Resolve<IAccountDAL>();

int count = iaccount.Count(newValue);

if (count>0)
{
MessageBox.Show("账套名称重复,请重新命名!", "警告", MessageBoxButton.OK);
(e.EditingElement as TextBox).Text = ZTName;
return;
}
else
{
int id = (this.dgData.SelectedItem as Founder.Model.Account.ModelAccountInfo).AccountID;
if (!iaccount.UpdateZTName(newValue,id))
{
MessageBox.Show("更新账套名称失败,请重试!","提示",MessageBoxButton.OK);
}
}
//判断是否重复

}

}

private string ZTName = string.Empty;
private void BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
ZTName = (this.dgData.SelectedItem as Founder.Model.Account.ModelAccountInfo).Name;
//MessageBox.Show(ZTName);
}

总结:该功能比较简单,主要就是熟悉DataGrid的熟悉和方法。在此,仅作记录。

posted @ 2019-02-27 16:33  野狼谷  阅读(8591)  评论(1编辑  收藏  举报