In WPF, how do I get the current background button theme?

In my wpf application, I need to get the background image of a theme button in order to paint the background of another control.

I tried to access PresentationFramework.Aero.dll and use ButtonChrome, but so far no luck.

I also tried using VisualStyleRenderer, but it seems that this class can only be used to paint the background (I cannot get a brush and set it as the background of another control).

Any ideas?

Regards, Eduardo Melo

+5
source share
1 answer

This can be done in code by looking at the default button style in resources:

    private static object GetValueFromStyle(object styleKey, DependencyProperty property)
    {
        Style style = Application.Current.TryFindResource(styleKey) as Style;
        while (style != null)
        {
            var setter =
                style.Setters
                    .OfType<Setter>()
                    .FirstOrDefault(s => s.Property == property);

            if (setter != null)
            {
                return setter.Value;
            }

            style = style.BasedOn;
        }
        return null;
    }

    ...

    this.Background = GetValueFromStyle(typeof(Button), BackgroundProperty) as Brush;

XAML, :

public class ValueFromStyleExtension : MarkupExtension
{
    public ValueFromStyleExtension()
    {
    }

    public object StyleKey { get; set; }
    public DependencyProperty Property { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (StyleKey == null || Property == null)
            return null;
        object value = GetValueFromStyle(StyleKey, Property);
        if (value is MarkupExtension)
        {
            return ((MarkupExtension)value).ProvideValue(serviceProvider);
        }
        return value;
    }

    private static object GetValueFromStyle(object styleKey, DependencyProperty property)
    {
        Style style = Application.Current.TryFindResource(styleKey) as Style;
        while (style != null)
        {
            var setter =
                style.Setters
                    .OfType<Setter>()
                    .FirstOrDefault(s => s.Property == property);

            if (setter != null)
            {
                return setter.Value;
            }

            style = style.BasedOn;
        }
        return null;
    }
}

XAML

Background="{util:ValueFromStyle StyleKey={x:Type Button}, Property=Control.Background}">

EDIT: ValueFromStyleExtension , DynamicResource ( ME)

+9

All Articles