简体   繁体   中英

Serialize a UserControl to xaml, but not its children?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM