如何在代码中从模板对象获得实际的XAML ?



不确定这是否可能,但如果我有一个模板对象(传递给OnApplyTemplate覆盖)是否有任何方法我可以检查XAML的字符串表示构成?我在内部知道当模板的XAML被编译时,它实际上被转换为BAML,并且我知道当代码到达覆盖时,它既不是,因为它已经被重新水合成实际对象,这就是我问的原因。

实际上,如果你可以从一个模板对象到XAML,那么理论上你不能从任何WPF对象到它的XAML表示吗?不过,我还是选择前者作为模板。

这是。net 4.0中的c#,而不是Silverlight fww。

旧的XamlWriter类大多数时候都可以工作。新的XAML类,在System。当试图将ControlTemplate序列化为Xaml时,由于某种原因抛出错误。我建议您避免在生产代码中依赖任何XAML编写…

var template = this.FindResource("MyTemplate") as ControlTemplate;
// The new XamlServices class throws an error. 
//string xaml = System.Xaml.XamlServices.Save(template);
// The old XamlWriter from the Markup namespace works (usually)
string xaml = System.Windows.Markup.XamlWriter.Save(template);
// Format the XAML so that it's readable.
string indentedXaml = XElement.Parse(xaml).ToString();
Console.WriteLine(indentedXaml);

最新更新