gpt4 book ai didi

c# - 在 WPF 中,如何获取当前主题的按钮背景?

转载 作者:太空狗 更新时间:2023-10-29 21:19:56 26 4
gpt4 key购买 nike

在我的 wpf 应用程序中,我需要获取主题的按钮背景画笔来绘制另一个控件的背景。

我已尝试引用 PresentationFramework.Aero.dll 并使用 ButtonChrome,但到目前为止运气不佳。

我也尝试过使用 VisualStyleRenderer,但似乎这个类只能用于绘制背景(我无法获取画笔并将其设置为另一个控件的背景)。

有什么想法吗?

亲切的问候,爱德华多·梅洛

最佳答案

可以通过在资源中查找默认按钮样式在代码中完成:

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

编辑:修复了 ValueFromStyleExtension 值被定义为 DynamicResource(或另一个 ME)的情况

关于c# - 在 WPF 中,如何获取当前主题的按钮背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4198500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com