Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Embed Custom GUIs in WPF


Serialization/Deserialization

Go to the WPF Compound Documents sample app. Select Edit/Insert PhotoControl. Click on the PhotoControl's Add button and add some JPEG files. Look at the XAML markup in the RichTextBox on the right. You'll see that several of the PhotoControl's XAML elements have Name attributes. But you can save and open the document by selecting File/Save and File|Open without encountering the dreaded XamlParseException. How?

This sample application uses PlaceholderControls, which are minimalist UserControls with no content. PlaceholderControls have the same Name attribute value as the UserControls that they represent. The program avoids the deserialization issue by simply replacing all UserControls with PlaceholderControls before serializing the document, and replacing all PlaceholderControls with UserControls after deserializing. Converting between UserControls and PlaceholderControls is done by the ReplaceControlsWithPlaceholders and ReplacePlaceholdersWithRealControls methods (Listing One). ReplaceControlsWithPlaceholders first calls GetUserControlNames, which scans the specified document fragment and retrieves a list of UserControl Name attribute values in the order in which the UserControls appear in the fragment. Then it uses a regular expression to replace the UserControl markup with PlaceholderControl markup. ReplacePlaceholdersWithRealControls scans through the entire document looking for BlockUIContainers and InlineUIContainers because those elements contain each of the document's PlaceholderControls. If it finds a BlockUIContainer or InlineUIContainer that contains a PlaceholderControl, it extracts the PlaceholderControl. Then it determines the type of UserControl represented by the PlaceholderControl. Finally, it creates the UserControl and loads it with state data so that it displays properly.

// Convert UserControls into PlaceholderControls in the xaml markup.
public static string ReplaceControlsWithPlaceholders(string xaml, 
                              TextPointer start, TextPointer end)
{
  string modifiedMarkup = xaml;
  // Get a list of UserControl Name attribute values in the 
  // order in which they appear in the document.
  List<string> userControlNames = GetUserControlNames(start, end);
  // Search for each Name... 
  foreach (string name in userControlNames)
  {
    foreach (string typeName in ControlTypeNames)
    {
      string enhancedUserControl = 
    string.Format(@"<{0} .*?Name=""{1}"".*?</{0}>", typeName, name);
      string placeHolderControl = 
         string.Format(@"<wpfcd:PlaceholderControl 
             Name=""{0}"" Visibility=""Hidden""/>", 
      Regex enhancedUserControlRegex = new Regex(enhancedUserControl);
      // Replace the UserControl with a Placeholder control having 
      // the same Name as the UserControl.
      modifiedMarkup = enhancedUserControlRegex.Replace(
            modifiedMarkup, placeHolderControl);
    }
  }
  return modifiedMarkup;
}
// Convert all PlaceholderControls in the document with
// the UserControls that they represent.
public static void ReplacePlaceholdersWithRealControls(
        FlowDocument document, RichTextBox richTextBox)
{
  int replacements = 0;
  TextPointer current = document.ContentStart;
  // Scan through the entire document...
  while (current.CompareTo(document.ContentEnd) < 0)
  {
    // UserControls will be nested in BlockUIContainer
    // or InlineUIContainer XAML elements.
    BlockUIContainer blockUIContainer = current.Parent as 
    InlineUIContainer inlineUIContainer = current.Parent as 
    // If we found a BlockUIContainer or InlineUIContainer...
    if (blockUIContainer != null || inlineUIContainer != null)
    {
      PlaceholderControl placeHolderControl;
      if (blockUIContainer != null)
      {
        placeHolderControl = 
           blockUIContainer.Child as PlaceholderControl;
      }
      else
      {
        placeHolderControl = inlineUIContainer.Child as 
      }
      // If we found a PlaceholderControl...
      if (placeHolderControl != null)
      {
        // Determine the type of the UserControl that the 
        // PlaceholderControl represents.
        Type controlType = 
      EnhancedUserControlUtils.GetType(placeHolderControl.Name);
        // Create a new UserControl of the proper type.
        IEnhancedUserControl newControl = 
        EnhancedUserControlUtils.ControlFactory(controlType);
        // Change the name of the new control so that it won't
        // overwrite another control's data.
        newControl.Name = 
        EnhancedUserControlUtils.NameFromGuid(Guid.NewGuid());
        // Retrieve the UserControl's state data.
        ICloneable dataToPersist = 
            (ICloneable)EnhancedUserControlUtils.
                       Load(placeHolderControl.Name);
        // Clone the state data so that the new UserControl
        //  won't overwrite another UserControl's data.
        ICloneable newObject = (ICloneable)dataToPersist.Clone();
        // Save the new UserControl's type and state.
        Globals.CompoundDocument.PersitedTypes[newControl.Name] = 
        Globals.CompoundDocument.PersitedValues[newControl.Name] = 
        // Load the new UserControl with its state data.
        ((IEnhancedUserControl)newControl).Load(newObject);
        // Nest the new UserControl inside the BlockUIContainer
        // or InlineUIContainer.
        if (blockUIContainer != null)
        {
          blockUIContainer.Child = (UserControl)newControl;
        }
        else if (inlineUIContainer != null)
        {
          inlineUIContainer.Child = (UserControl)newControl;
        }
        replacements++;
      }
    }
   current=current.GetNextContextPosition(LogicalDirection.Forward);
  }
  ...
}
Listing One


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.