0
我在DataGrid中可編輯單元格,我需要創建「撤消更改」按鈕,設置原值細胞的TextBlock的。意外行爲在DataGridCell內的TextBlock(文本框)後,「撤銷更改」
有沒有可能性DataGridCell有兩個不同的TextBlocks(或文本框)?如果是這樣,爲什麼有可能,其中一個重寫另一個?
這裏是我的代碼部分,我做「撤消更改」
private void ContextMenuDeleteItemClick(object sender, RoutedEventArgs e)
{
var cellInfo = this.CurrentCell;
this.ScrollIntoView(cellInfo.Item);
var row = this.ItemContainerGenerator.ContainerFromItem(cellInfo.Item) as DataGridRow;
if (row != null)
{
FrameworkElement element = cellInfo.Column.GetCellContent(cellInfo.Item);
KeyValuePair<DataGridColumn, DataGridRow> key = new KeyValuePair<DataGridColumn, DataGridRow>(cellInfo.Column, row);
if (originalCellValues.ContainsKey(key))
{
((element.Parent as DataGridCell).Content as TextBlock).Text = originalCellValues[key];
(element.Parent as DataGridCell).Style = (element.Parent as DataGridCell).Column.CellStyle;
}
}
}
當我試圖抓住這一行爲同時調試,我OnBeginningEdit值都很好,然後突然在OnCellEditEnding值是意外
在我OnBeginningEdit我保存原始值
protected override void OnBeginningEdit(DataGridBeginningEditEventArgs e)
{
if (!this.editableColumns[e.Column.DisplayIndex])
{
if (!e.Row.IsNewItem)
{
e.Cancel = true;
}
}
FrameworkElement element = e.Column.GetCellContent(e.Row);
KeyValuePair<DataGridColumn, DataGridRow> key = new KeyValuePair<DataGridColumn, DataGridRow>(e.Column, e.Row);
if (!originalCellValues.ContainsKey(key))
{
originalCellValues.Add(key, ((element.Parent as DataGridCell).Content as TextBlock).Text);
}
}
在我OnCellEditEnding我更改單元格的風格 - 一個色彩單元,如果它被編輯
protected override void OnCellEditEnding(DataGridCellEditEndingEventArgs e)
{
if ((e.EditingElement as TextBox).Text != originalCellValues[new KeyValuePair<DataGridColumn, DataGridRow>(e.Column, e.Row)])
{
FrameworkElement element = e.Column.GetCellContent(e.Row);
(element.Parent as DataGridCell).Style = CreateStyle("RequiredColor", e.Column.CellStyle);
}
else
{
FrameworkElement element = e.Column.GetCellContent(e.Row);
(element.Parent as DataGridCell).Style = e.Column.CellStyle;
}
}