Data loss during WPF clipboard operations
I am working with a FlowDocument
in a WPF RichTextBox
. Some of the flow document elements are created using subclasses of the System.Windows.Documents
framework classes and all of the elements use the Tag
property to store additional data.
If I use a XamlWriter to serialize a document tree, everything is correctly reflected in the resulting Xaml
output.
However, if I simply copy and paste within the RichTextBox
, although the pasted elements are visually identical to those from which they were copied, the clipboard operation discards all my additional data. Specifically, all the subclassed elements are pasted as instances of their base framework types and none of them have data in their Tag
property.
This suggests that a WPF clipboard operation on a RichTextBox
does not use XamlWriter
for serialization, despite the fact that the serialized clipboard data identifies its format as "Xaml".
I imagine that the reason for this behavior is to ensure a common denominator when pasting into other Xaml-aware applications that do not necessarily have knowledge of my custom types. But I need to implement a richer copy / paste mechanism for use within my application.
I guess I can probably intercept the copy event and add clipboard data in a custom format, which is subsequently applied in the paste event. However, this presents its own complications, as elements may need to be wrapped before pasting (for example inline elements that are pasted into a block element context).
So, I am hoping开发者_运维知识库 to avoid reinventing the wheel and would appreciate any advice on how to get this to work using the existing framework infrastructure.
I don't have an exact answer to your question but I can think of two ways to proceed with -
Associate a
CommandBinding
for Copy/Paste operation, with your controls and perform custom operations inExecute
andCanExecute
methods. As explained here:http://msdn.microsoft.com/en-us/library/system.windows.input.commandbinding.aspx
Use
DataObject
class to intercept the Copy/Paste events and perform your custom operation there. i.e.DataObject.AddCopyingHandler
andDataObject.AddPastingHandler
.Some useful links -
http://msdn.microsoft.com/en-us/library/system.windows.dataobject_members.aspx
http://blogs.msdn.com/b/prajakta/archive/2006/11/28/auto-detecting-hyperlinks-in-richtextbox-part-ii.aspx
Hope that will help.
精彩评论