Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply a style to all buttons?

How and where do I create a style that gives all button controls that have resource blue (yellow border, blue background)?

Can it also be added to a texbox as well?

Is there a centralized place, since I would want this style to be able affect buttons in different pages in my app?

like image 928
Jason94 Avatar asked Oct 19 '25 01:10

Jason94


1 Answers

In these cases you may use Styles:

  • You are going to apply same properties (or members) on several controls of a type
  • You are going to make save good and desired state of a type and use it later.

You can add this Style in control's resources or ResourceDictionaries like this:

<Style TargetType="Button">
    <Setter Property="BorderBrush" Value="Yellow"/>
    <Setter Property="Background" Value="Blue"/>
</Style>

If you define x:key, then you should explicitly say that which button follows your style (e.g. <Button Style="{StaticResource myButtonStyleKey}">) otherwise your style will be automatically apply on buttons.

EDIT: Add a ResourceDictionary (named myStyles.xaml) to your project (In a folder named MyResource). Here is the code:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button">
        <Setter Property="BorderBrush" Value="Yellow"/>
        <Setter Property="Background" Value="Blue"/>
    </Style>
</ResourceDictionary> 

Then in your App.xaml add this:

<Application x:Class="WPFApp.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="MyResource/myStyles.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>
like image 197
Hossein Narimani Rad Avatar answered Oct 20 '25 15:10

Hossein Narimani Rad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!