在WPF中,我怎么了当前主题的按钮背景? [英] In WPF, how do I get the current theme's button background?
问题描述
在我的WPF应用程序,我需要获得主题的按钮背景画笔画出另一个控制的背景。
In my wpf application, I need to get the theme's button background brush to draw the background of another control.
我曾尝试引用PresentationFramework.Aero.dll和使用ButtonChrome,但至今没有运气。
I have tried referencing PresentationFramework.Aero.dll and using ButtonChrome, but no luck so far.
我使用VisualStyleRenderer也尝试过,但似乎这个类只能用于绘制背景(我可以'吨得到画笔,将其设置为另一个控件的背景)。
I've tried using VisualStyleRenderer also, but it seems that this class can be used only to draw the background (I can't get a brush and set it as the background of another control).
任何想法?
亲切的问候,
·爱德华多·梅洛
Kind Regards, Eduardo Melo
推荐答案
可以在代码中通过查找资源的默认按钮样式做的:
It can be done in code by looking up the default button style in the 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中,你可以轻松地创建从上面的代码标记扩展:
If you need to do it in XAML, you can easily create a markup extension from the code above:
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}">
编辑为在那里的值被定义为 DynamicResource
(或另一个ME)
fixed ValueFromStyleExtension
for the case where the value is defined as a DynamicResource
(or another ME)
这篇关于在WPF中,我怎么了当前主题的按钮背景?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!