Serialize a UserControl to xaml, but not its child

2019-05-26 15:05发布

问题:

There were quite a few changes made to the XAML serialization stack in .NET 4.0. One of the changes is that when you serialize a UserControl, not only do you get the control itself, but you also get all of its children.

var sb = new StringBuilder();
var writer = XmlWriter.Create(sb, new XmlWriterSettings
{
    Indent = true,
    ConformanceLevel = ConformanceLevel.Fragment,
    OmitXmlDeclaration = true
});
var mgr = new XamlDesignerSerializationManager(writer);
mgr.XamlWriterMode = XamlWriterMode.Expression;
System.Windows.Markup.XamlWriter.Save(this, mgr);
return sb.ToString();

Instead of getting, for example,

<MyUserControl 
    xmlns="clr-namespace:MyNamespace" 
    SomeProperty="Add ten thousand child controls" />

You now get

<MyUserControl 
    xmlns="clr-namespace:MyNamespace" 
    SomeProperty="Add ten thousand child controls">
    <StackPanel xmlns="http://microsoft.com/something/xaml/dude">
          <TextBlock Text="Child Control ONE!"/>
          <TextBlock Text="Child Control TWO!"/>
          <TextBlock Text="Child Control THREE!"/>
          <!--WTMFH?-->
      <TextBlock Text="Child Control TEN FRIGGEN THOUSAND!"/>
    </StackPanel>
</MyUserControl/>

How can I revert this behavior back to the original method?

回答1:

One option I have is to override ShouldSerializeContent and return false. Still looking for better answers that will allow me to specify this outside of the control.