I am writing a class that will convert a HTML document to a list of Paragrpahs that can be used with RichTextBlock in Windows 8 apps. I want to be able to give the class a list of Styles defined in XAML and the class will read useful properties from the style and apply them.
If I have a Windows.UI.XAML.Style style
how do I read a property from it? I tried
var fontWeight = style.GetValue(TextElement.FontWeightProperty)
for a style
defined in XAML with TargetProperty="TextBlock" but this fails with and exception
You could try this:
var fontWeightSetter =
style.Setters.Cast<Setter>().FirstOrDefault(
setter => setter.Property == TextElement.FontWeightProperty);
var fontWeight =
fontWeightSetter != null ?
(FontWeight)fontWeightSetter.Value :
FontWeights.Normal;
Or check if that works:
public static class StyleExtensions
{
// Untested
public static object GetPropertyValue(this Style style, DependencyProperty property)
{
var setter =
style.Setters.Cast<Setter>().FirstOrDefault(
s => s.Property == property);
var value = setter != null ? setter.Value : null;
if (setter == null &&
style.BasedOn != null)
{
value = style.BasedOn.GetPropertyValue(property);
}
return value;
}
}