申请一个WPF样式为多个控件 [英] Applying a WPF Style to multiple controls

查看:169
本文介绍了申请一个WPF样式为多个控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题可能是重复的,但我无法找到它的左右。

This question is probably a duplicate, but I couldn't find it on SO.

如果我有一个容器窗口的StackPanel 电网等,有没有什么办法,我可以申请一个风格来某种类型的一切都包含在它的控制,?

If I have a container Window, StackPanel, Grid, etc. is there any way I can apply a Style to all the controls of a certain type, that are contained within it?

我可以使用 Container.Resources 和个人的变化设置为的TargetType ,但是当应用属性更改,我试着设置风格的目标,我得到一个错误,告诉我​​,我不能设置风格

I can apply property changes, by using Container.Resources and setting individual changes to a TargetType, but when I tried setting the Style of the target, I get an error, telling me I can't set Style.

有没有办法做到这一点在XAML?

Is there any way to do this in XAML?

推荐答案

排序的,这取决于你正在努力设置什么。如果属性是一个共同的基类的属性,然后是的,可以。您还可以在WPF比Silverlight中更多的选择,因为你可以继承的风格。例如...

Sort of, depending on what you are trying to set. If the properties are properties of a common base class then yes, you can. You also have more options in WPF than Silverlight because you can inherit styles. For example...

<Window.Resources>
    <Style x:Key="CommonStyle" TargetType="FrameworkElement">
        <Setter Property="Margin" Value="2" />
    </Style>
    <Style TargetType="StackPanel" BasedOn="{StaticResource CommonStyle}">
    </Style>
    <Style TargetType="Grid" BasedOn="{StaticResource CommonStyle}">
    </Style>
    <Style TargetType="Button" BasedOn="{StaticResource CommonStyle}">
        <Setter Property="Background" Value="LimeGreen" />
    </Style>
</Window.Resources>

常见的风格, CommonStyle 将由3含蓄的风格继承。但是,你只能指定适用于所有FrameworkElement的类的属性。你不能设置背景CommonStyle因为FrameworkElement上不提供背景属性。因此,即使网格和StackPanel中有背景(从面板继承)它不是按钮具有相同背景属性(从Control继承。)

The common style, CommonStyle would be inherited by the 3 implicit styles. But you can only specify properties that are common to all FrameworkElement classes. You couldn't set Background in CommonStyle because FrameworkElement does not provide a Background property. So even though Grid and StackPanel have Background (inherited from Panel) it is not the same Background property that Button has (inherited from Control.)

希望这有助于让你对你的方式。

Hope this helps get you on your way.

这篇关于申请一个WPF样式为多个控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆