Applying a WPF Style to multiple controls

[亡魂溺海] 提交于 2019-12-18 14:09:35

问题


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

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?

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.

Is there any way to do this in XAML?


回答1:


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>

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.



来源:https://stackoverflow.com/questions/4675255/applying-a-wpf-style-to-multiple-controls

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