将标记扩展速记语法转换为完整的Xml表单

时间:2014-02-26 07:24:54

标签: c# wpf xaml markup-extensions

我有XAML字符串,如:

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

如何将所有大括号转换为代码中的元素,如:

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

1 个答案:

答案 0 :(得分:2)

您可以使用XamlReaderXamlWriter我认为(!)默认情况下不会保存速记种类。见http://msdn.microsoft.com/en-us/library/system.windows.markup.xamlreader(v=vs.110).aspx

其中包含一个示例

// 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);
上面的

保存按钮看起来像

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