WPF - 全球风格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3569974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:04:08  来源:igfitidea点击:

WPF - Global Style?

wpfxamlstylesglobal

提问by Sonny Boy

Is there a way to setup global styles for my WPF application?

有没有办法为我的 WPF 应用程序设置全局样式?

What I'm hoping to do is apply a style to all my Buttons that also have an Image child.

我希望做的是将样式应用于所有也有 Image 子项的按钮。

回答by Goblin

Well, sort of - it's a catch-all approach you can do - put the following element in your App.xaml - all your buttons will change (except the ones you apply a style to, manually).

嗯,有点 - 这是你可以做的一个包罗万象的方法 - 将以下元素放在你的 App.xaml 中 - 你的所有按钮都会改变(除了你手动应用样式的按钮)。

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="LightPink"/> <!-- You should notice that one... -->
</Style>

However, if you want to hit only buttons with images - you have to inherit from Button everytime you do and then apply a style like this:

但是,如果您只想点击带有图像的按钮 - 您每次都必须从 Button 继承,然后应用如下样式:

public class CustomImageButton:Button{}
<Style TargetType="{x:Type local:CustomImageButton}">
    <Setter Property="Background" Value="LimeGreen"/>
</Style>
<local:CustomImageButton Content="ClickMe"/>

It is a very coarse-grained global styling - and you need to follow the convention to make it work.

这是一个非常粗粒度的全局样式 - 您需要遵循约定才能使其工作。

An alternative is to use Themes - read more about that here.

另一种方法是使用主题 -在此处阅读更多相关信息。

回答by Brad Cunningham

You can do implicit styles in WPF which are applied by type

您可以在 WPF 中执行按类型应用的隐式样式

for instance

例如

<Style TargetType="Button">

Will be applied to ALL the buttons within the scope of that style (If the style is in App.XAML it will apply to all buttons, if it is lower in the chain it will apply to all buttons underneath it)

将应用于该样式范围内的所有按钮(如果样式在 App.XAML 中,它将应用于所有按钮,如果它在链中较低,它将应用于其下方的所有按钮)

If you want to apply it to only certain types of buttons (say imagebuttons) create a type that derives from button (call it ImageButton) and then create a style targeted to that type.

如果您只想将其应用于某些类型的按钮(例如图像按钮),请创建一个派生自按钮的类型(称为 ImageButton),然后创建一个针对该类型的样式。

回答by samkass

Put the style into a ResourceDictionary tag inside your App.xaml and it will apply to the entire app.

将样式放入 App.xaml 中的 ResourceDictionary 标记中,它将应用于整个应用程序。