我有一个DataGrid,其中包含我在代码中添加的不同类型的列。我已经将标准数据网格子类化,以便我可以覆盖OnExecutedPaste方法等。但是,这仅在用户粘贴而没有单元格处于编辑模式时触发;如果单元格处于编辑模式,则剪贴板内容将粘贴到单元格中。我想捕获粘贴事件,以便如果剪贴板包含多个值(例如来自Excel的数据),那么我可以将每个值放在不同的单元格中。
我可以在单元格处理之前拦截粘贴事件吗?希望没有子类化所有列并实现我自己的单元格生成等等!
答案 0 :(得分:2)
您可能不需要继承Grid。这更像是一个WinForms的东西。我不知道你需要什么样的columntypes,但也许这可以指出你正确的方向:
DataObject.AddPastingHandler(yourControl,PastingHandler);
您可以创建从DataGridBoundColumn派生的自定义ColumnType。这很简单,然后将pastinghandler附加到editcontrol。
namespace StackOverflow
{
public class CustomColumn : DataGridBoundColumn
{
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
TextBlock block = new TextBlock();
CustomColumn column = (CustomColumn)cell.Column;
Binding binding = (Binding)column.Binding;
if (binding != null)
{
// Binde den ausgewählten Wert
Binding cellBinding = new Binding(binding.Path.Path);
cellBinding.Source = dataItem;
cellBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
cellBinding.ValidatesOnDataErrors = true;
cellBinding.ValidatesOnExceptions = true;
cellBinding.NotifyOnValidationError = true;
cellBinding.ValidatesOnNotifyDataErrors = true;
cellBinding.Mode = BindingMode.OneWay;
block.SetBinding(TextBlock.TextProperty, cellBinding);
}
return block;
}
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem)
{
TextBox box = new TextBox();
CustomColumn column = (CustomColumn)cell.Column;
Binding binding = (Binding)column.Binding;
if (binding != null)
{
// Binde den ausgewählten Wert
Binding cellBinding = new Binding(binding.Path.Path);
cellBinding.Source = dataItem;
cellBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
cellBinding.ValidatesOnDataErrors = true;
cellBinding.ValidatesOnExceptions = true;
cellBinding.NotifyOnValidationError = true;
cellBinding.ValidatesOnNotifyDataErrors = true;
cellBinding.Mode = BindingMode.TwoWay;
box.SetBinding(TextBlock.TextProperty, cellBinding);
}
DataObject.AddPastingHandler(box, PastingHandler);
return box;
}
private void PastingHandler(object sender, DataObjectPastingEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox == null)
{
return;
}
if (e.DataObject.GetDataPresent(typeof(string)))
{
//Read input
string pasteText = e.DataObject.GetData(typeof(string)) as string;
// Kommt ein neuer String zurück, wird dieser eingefügt und die ursprüngliche Operation abgebrochen.
if (!string.IsNullOrEmpty(pasteText))
{
// Neuen Text einbringen
textBox.Text = pasteText;
// Restliches Einfügen abbrechen
e.CancelCommand();
}
}
}
}
}