How to set background color of button in WPF?

送分小仙女□ 提交于 2019-12-12 13:06:30

问题


How to set the background color of a button in xaml?

It can't be much harder than

<Button Margin="2" Background ="LightGreen" ....>

But this does not work...for the avoidance of confusion, button here is System.Windows.Controls.Button

Edit

I forgot to mention that I use DevExpress's ThemeManager but did not think that would cause issues as per DevExpress they do not style the standard Windows Buttons...apparently they do, however, which basically makes it impossible to change the background color of a button without some major work...


回答1:


According to documentation:

DevExpress provides multiple themes that can be applied to all DevExpress controls for WPF and some standard controls (GroupBox, ScrollViewer, Scroll, RadoiButton, Button, ListBox, Slider, TabControl, Separator, ToggleButton, RepeatButton, Label, ListBoxItem, TabItem, ToolTip, etc).

As you can see the Button control is listed here. But then in documentation it is said that you can disable theme of individual control by setting ThemeName attribute to None. So, you can just disable the theme for button or for some of its parent containers and use your own style.
Here is example:

<Button Margin="2" Background="LightGreen" dx:ThemeManager.ThemeName="None" ...>



回答2:


Try this:

yourBtn.Background = new SolidColorBrush(Colors.Green);

Or in XAML:

<Window.Resources>
   <SolidColorBrush x:Key="BG" Color="Green"/>
</Window.Resources>

<Button Background="{DynamicResource BG}"></Button>



回答3:


<Button Margin="2" Background="LightGreen"/> works. If it doesn't work for you, perhaps you have another style or style manager overriding it somewhere.

Additional information - Another answer shows how to style an individual button using dynamic resources. To set the background colour for all buttons in a style using a resourcedictionary, you can use something like:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!--background brush-->
    <LinearGradientBrush x:Key="backgroundBrush" StartPoint="0.5,0" EndPoint="0.5,1">
        <GradientStop Color="White" Offset="0.3"/>
        <GradientStop Color="#DDDDFF" Offset="1"/>
    </LinearGradientBrush>

        <!--The style for buttons-->
        <Style TargetType="Button">
            <Setter Property="Background" Value="{StaticResource backgroundBrush}"/>
        </Style>
    </ResourceDictionary>


来源:https://stackoverflow.com/questions/33213025/how-to-set-background-color-of-button-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!