从System.Windows.Style对象生成Xaml的工具?

时间:2014-06-12 14:06:18

标签: c# wpf xaml export

我有一个以编程方式生成的System.Windows.Style类型对象,我想将其导出为XAML代码,是否有人知道可以执行此操作的任何工具?我猜想,它有点像序列化,但如果已经存在某些内容,我不想自己写一个。

谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用XamlWriter

var style = new Style(typeof(Control));
style.Setters.Add(new Setter(Control.BackgroundProperty, Brushes.Red));

var xaml = XamlWriter.Save(style);

上面的代码创建了这个XAML:

<Style TargetType="Control"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Style.Resources>
        <ResourceDictionary />
    </Style.Resources>
    <Setter Property="Panel.Background">
        <Setter.Value>
            <SolidColorBrush>#FFFF0000</SolidColorBrush>
        </Setter.Value>
    </Setter>
</Style>