Igor Kulman
Igor Kulman

Reputation: 16361

How to read Windows.UI.XAML.Style properties in C#

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

Upvotes: 4

Views: 1132

Answers (1)

Filip Skakun
Filip Skakun

Reputation: 31724

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;
    }
}

Upvotes: 2

Related Questions