更改WPF窗口的所有按钮背景颜色

时间:2014-05-29 06:55:10

标签: wpf xaml

我正在尝试动态添加样式到按钮,下面是我正在使用的代码,但它不适合我

第一种方式

 public Login()
        {
            InitializeComponent();
             Style style = new Style
            {
                TargetType = typeof(Button)
            };

            style.Setters.Add(new Setter(Button.BackgroundProperty, Brushes.Red));
            Resources.Add(typeof(Button), style);


        }

第二种方式 还有一件事,我尝试过以下第二种方式,但它给了我错误在'SetterBase'使用(密封)后,它无法修改

Style style = this.FindResource("ButtonStyle1") as Style;

            Setter setter = (Setter)style.Setters[0];
            setter.Property. = false;
            Color orange1 = (Color)ColorConverter.ConvertFromString("#FFF3800C");
            setter.Value = new SolidColorBrush(orange1);

2 个答案:

答案 0 :(得分:1)

在Windows资源中添加

<Window.Resources>
    <Style TargetType="Button">
        <Setter Property="Background" Value="Red"></Setter>
    </Style>
</Window.Resources>

这将改变窗口中所有按钮的背景

答案 1 :(得分:0)

This article开始描述了一个解决方案,尽管它没有详细分解;你应该通过查看作者的代码here来找到所需的一切。

主类是ThemeManager,它提供了一种将主题应用于应用程序的方法。作者使用Theme类表示主题 - 重要的位是Uri属性。本质上,ThemeManager从Uri加载适当的资源文件,并将其添加到应用程序的MergedDictionaries集合中(首先删除任何现有的主题资源)。

因此,作者代码的浓缩(和未经测试)版本可能是这样的: -

private ResourceDictionary _currentTheme;

public void ApplyTheme(Uri uri)
{
    if (_currentTheme != null)
    {
        // Unload the current theme.
        Application.Current.Resources.MergedDictionaries.Remove(_currentTheme);
    }

    var resourceDictionary = 
        Application.LoadComponent(uri) as ResourceDictionary;
    if (resourceDictionary != null)
    {
        Application.Current.Resources.MergedDictionaries.Add(resourceDictionary);
        _currentTheme = resourceDictionary;
    }
}

Uri的一个例子是:

var uri = new Uri(
    "/Wpf.TestHarness;component/Themes/RedTheme.xaml", 
    UriKind.Relative);

其中Wpf.TestHarness是包含XAML资源文件的已编译程序集的名称(不带.DLL或.EXE扩展名),/Themes/RedTheme.xaml' is the path to one of the XAML theme files embedded in that project ( component`是此“pack URI”的必需部分路径表示法)。请记住将项目中XAML文件的构建操作设置为“页面”。

现在,在每个主题文件中创建一个名为“ButtonStyle1”的样式,但例如使用不同的背景颜色。在你的应用程序中,我认为你需要使用DynamicResource引用这些样式(如果我错了,有人会纠正我),例如: -

<Button Style="{DynamicResource ButtonStyle1}" ... />

更好的是,不要为你的风格命名。只需使用TargetType,将其应用于该类型的每个控件: -

<Style TargetType="{x:Type Button}">...</Style>
祝你好运!