Search code examples
c#wpfxamlmarkup-extensions

Convert Markup Extension Shorthand Syntax to Full Xml Form


I have XAML string like:

    <Button Content={Binding Name} Style={StaticResource ButtonStyle}/>

How I can convert all braces to elements in code like:

    <Button>
      <Button.Content>
         <Binding Path="Name">
      </Button.Content>
      <Button.Style>
         <StaticResource ResourceKey="ButtonStyle"/>
      </Button.Style>
    </Button>

Solution

  • You can use XamlReader and XamlWriter which I think(!) by default does not save the shorthand variety. See http://msdn.microsoft.com/en-us/library/system.windows.markup.xamlreader(v=vs.110).aspx

    which includes an example

    // Create the Button.
    Button originalButton = new Button();
    originalButton.Height = 50;
    originalButton.Width = 100;
    originalButton.Background = Brushes.AliceBlue;
    originalButton.Content = "Click Me";
    
    // Save the Button to a string. 
    string savedButton = XamlWriter.Save(originalButton);
    
    // Load the button
    StringReader stringReader = new StringReader(savedButton);
    XmlReader xmlReader = XmlReader.Create(stringReader);
    Button readerLoadButton = (Button)XamlReader.Load(xmlReader);
    

    saved button above looks like

     <Button Background="#FFF0F8FF" Width="100" Height="50" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">Click Me</Button>