Converting RTF on the Clipboard To XAML

Here is a simple function that will convert RTF data on the clipboard to XAML:

 

        ///<summary>

        /// Returns the text contents of the clipboard as XAML

        ///</summary>

        ///<returns></returns>

        public static string GetFormattedXamlFromClipboard() {

            System.Windows.Controls.RichTextBox box = new System.Windows.Controls.RichTextBox();

            box.SelectAll();

            box.Paste();

          box.SelectAll();

            box.Copy();

            return System.Windows.Clipboard.GetData(System.Windows.DataFormats.Xaml).ToString();

        }

 

Now you can easily copy-paste C# code and retrieve it as XAML, syntax highlighting preserved.

 

A better example would be converting an RTF file to XAML. To do it you have to load the file in a RichTextBox and then use this line:

return System.Windows.Clipboard.GetData(System.Windows.DataFormats.Xaml).ToString();

 

to extract the XAML.

For information on working with WPF RichTextBox: loading, saving data and such - see here.