我有一個包含多行和多列的數據網格。其中一列是數值。用戶可以編輯此列以更改此單元格/列中的值。此列已合計並且該數字顯示在數據網格下。只要用戶輸入號碼,我想要更新此號碼。在KeyUp事件中,我調用一個例程,將數據網格卸載到數據表中,然後讀取該列並計算此列中的值。但是,當datagrid卸載時,原始值仍然是單元格值。在卸載datagsrid之前是否有強制更新?在WPF中可以強制更新keyup事件上的數據網格嗎?
這裏是我的代碼:
private void dtGrid_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
int intKeyValue;
try
{
if (dtGrid.CurrentColumn.DisplayIndex == 1)
{
if (e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Tab || e.Key == Key.NumLock)
{
SendKeys.SendWait("{TAB}");
}
else
{
intKeyValue = GetNumericValue(e.Key.ToString());
if (e.Key == Key.LeftShift || e.Key == Key.RightShift || e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl)
{
e.Handled = true;
}
else
{
if (intKeyValue < 0 || intKeyValue > 9)
{
System.Windows.MessageBox.Show("Only numbers are allowed.");
e.Handled = true;
}
}
}
}
}
catch (Exception ex)
{
string strMsg = "Error occured in Start Row key event. ";
System.Windows.MessageBox.Show(strMsg + ex.Message);
//throw new NotImplementedException();
}
}
private void dtGrid_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
e.Handled = true;
UpdateRowSize();
}
private void UpdateRowSize()
{
DataTable dtFieldSizes = new DataTable();
int intRowSize;
string strTotalRowSizeData;
string[] strRowSizeInfo;
try
{
intRowSize = 0;
dtGrid.UpdateLayout();
dtFieldSizes = ((DataView)dtGrid.ItemsSource).ToTable();
for (int intRowCnt = 0; intRowCnt < dtFieldSizes.Rows.Count; intRowCnt++)
{
intRowSize += Convert.ToInt16(dtFieldSizes.Rows[intRowCnt]["Size"]);
}
strTotalRowSizeData = lblRowSize.Content.ToString();
strRowSizeInfo = strTotalRowSizeData.Split(':');
if (Convert.ToInt16(strRowSizeInfo[1]) != intRowSize)
{
lblRowSize.Content = strRowSizeInfo[0] + ": " + Convert.ToString(intRowSize);
}
}
catch (Exception ex)
{
string strMsg;
strMsg = "RefreshRowSize, error '" + ex.Message + "' has occurred.";
System.Windows.MessageBox.Show(strMsg);
}
}
完全的WinForms式思維嘗試。用'Template'試試'ItemsControl'。 –