剪贴板的序列化和反序列化(复制/粘贴)

时间:2015-02-10 16:40:24

标签: c# wpf

我正在尝试将复制/粘贴功能添加到我的WPF应用程序中。我有一个DataGrid,我允许选择整行。行是AcquisitionParameters类型的对象。选择还可以,复制到剪贴板也是如此。复制到剪贴板后,我验证数据是否已经很好地序列化,并且是这种情况。但是当我尝试从剪贴板中检索对象时,我无法以原始格式反序列化它,而是以CSV格式反序列化。

private void dataGridAcquisitions_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
{
   System.Windows.Clipboard.Clear();
   DataFormat format = System.Windows.DataFormats.GetDataFormat(typeof(AcquisitionParameters).FullName);

   System.Windows.IDataObject dataObj = new System.Windows.DataObject();
   dataObj.SetData(format.Name, (AcquisitionParameters)e.Item, false);
   System.Windows.Clipboard.SetDataObject(dataObj, true);
   bool ispresent = dataObj.GetDataPresent(format.Name); // ok
   AcquisitionParameters parameters = dataObj.GetData(format.Name) as AcquisitionParameters; //ok
   if(parameters != null && ispresent)
   {
      //enter here
   }
}


private void dataGridAcquisitions_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
   if (e.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
   {
      System.Windows.IDataObject dataObj = System.Windows.Clipboard.GetDataObject(); //type of AcquisitionParameters not available, only HTML, CSV, etc.
      string format = typeof(AcquisitionParameters).FullName;

      if(dataObj.GetDataPresent(format)) //false
      {
         AcquisitionParameters parameters = dataObj.GetData(format) as AcquisitionParameters;
         if(parameters != null)
         {
         }
      }            
   }
}

我的AcquisitionParameters类的声明

namespace App
{
   [Serializable]
   public class AcquisitionParameters
   {
      private double pulse;
      public double Pulse
      {
         get { return pulse; }
         set { pulse = value; }
      }

      private double range;
      public double Range
      {
         get { return range; }
         set { range = value; }
      }

      private double offset;
      public double Offset
      {
         get { return offset; }
         set { offset = value; }
      }
   }
}

1 个答案:

答案 0 :(得分:0)

尝试访问Clipboard中的数据,如下所示:

object data = Clipboard.GetData("AcquisitionParameters");
if (data != null) return (AcquisitionParameters)data;
return new AcquisitionParameters();

更新>>>

如果这没有帮助,请尝试设置如下数据:

DataObject dataObject = new DataObject();
dataObject.SetData("AcquisitionParameters", (AcquisitionParameters)e.Item, false);
Clipboard.SetDataObject(dataObject);