[英]In WPF is it possible to force an update to a datagrid on keyup event?
我有一個具有多個行和列的數據網格。 列之一是數值。 用戶可以編輯此列以更改此單元格/列中的值。 此列總計,並且數字顯示在數據網格下。 我想在用戶輸入號碼后立即更新此號碼。 在KeyUp事件上,我調用了一個例程,該例程將datagrid卸載到數據表中,然后讀取該列並計算該列中的值。 但是,當卸載數據網格時,原始值仍然是單元格值。 在卸載datagsrid之前是否有強制執行更新的方法?
這是我的代碼:
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);
}
}
您可以處理AutoGeneratingColumn
並將Binding列的UpdateSourceTrigger設置為PropertyChanged
。 假設這是您的數據表:
var tab = new DataTable();
tab.Columns.Add("a", typeof(double));
tab.Rows.Add(tab.NewRow());
tab.Rows[0][0] = 45;
這是您的DataGrid及其ItemsSource:
DataGrid gr = new DataGrid();
gr.ItemsSource = tab.AsDataView();
處理:
gr.AutoGeneratingColumn += Gr_AutoGeneratingColumn;
在其中
private void Gr_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
DataGridTextColumn col = e.Column as DataGridTextColumn;
if (col != null)
{
Binding binding = new Binding("[" + col.Header.ToString() + "]");
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
col.Binding = binding;
}
}
在此設置中,當您鍵入單元格時,DataGrid的值將更新。
您可以嘗試使用DataGridCell的keyup / keydown事件,而不是更新值datagrid keydown / up事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.