开发者

How to store a Collection of Objects in the Clipboard?

开发者 https://www.devze.com 2023-01-08 20:01 出处:网络
I have a class Slide, of which I want to place several instances in the clipboard. It works perfectly fine for a single instance.

I have a class Slide, of which I want to place several instances in the clipboard. It works perfectly fine for a single instance.

But when I try to, for example, put a List<Slide> in the clipboard, the SetDataObject call will silently fail.

Internally, a COMException will b开发者_Go百科e thrown and is swallowed. This is because List does not implement ISerializeable.

So, List<T> seems not to be an option. What would be the proper approach to place a collection of Slide instances in the clipboard?


ArrayList is serializable. While you lose the strong typing, you can always cast on the way out.


Turns out my assumptions were incorrect. I simply forgot a ToList() call and was only passing in the IEnumerable to SetData. After adding that, it is put into the clipboard just fine.

This is the code I ended up using back then:

public void CopySelectedSlidesToClipboard() {
  // Construct data format for Slide collection
  DataFormats.Format dataFormat = DataFormats.GetFormat( typeof( List<Slide> ).FullName );

  // Construct data object from selected slides
  IDataObject dataObject = new DataObject();

  List<Slide> dataToCopy = SelectedSlides.ToList();
  dataObject.SetData( dataFormat.Name, false, dataToCopy );

  // Put data into clipboard
  Clipboard.SetDataObject( dataObject, false );
}

public void PasteSlidesFromClipboard() {
  // Get data object from the clipboard
  IDataObject dataObject = Clipboard.GetDataObject();
  if( dataObject != null ) {
    // Check if a collection of Slides is in the clipboard
    string dataFormat = typeof( List<Slide> ).FullName;
    if( dataObject.GetDataPresent( dataFormat ) ) {
      // Retrieve slides from the clipboard
      List<Slide> slides = dataObject.GetData( dataFormat ) as List<Slide>;
      if( slides != null ) {
        Slides = Slides.Concat( slides ).ToList();
      }
    }
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消