Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a WPF Style to multiple controls

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?

like image 589
ocodo Avatar asked Jan 12 '11 23:01

ocodo


People also ask

How do I apply multiple styles in WPF?

To apply the multiple styles as you phrase it above, the best bet is to use triggers. In future version of WPF, the VisualStateManager will be introduced which supports the visual state transition between different set of setters, triggers, and animations which could enable a broader styling scenarios.

How do I style in WPF?

Template property, you can use a style to define or set a template. Designers generally allow you to create a copy of an existing template and modify it. For example, in the Visual Studio WPF designer, select a CheckBox control, and then right-click and select Edit template > Create a copy.

How can I access a control in WPF from another class or window?

Access of the controls from within the same assembly is hence allowed. If you want to access a control on a wpf form from another assembly you have to use the modifier attribute x:FieldModifier="public" or use the method proposed by Jean.


1 Answers

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.

like image 66
Josh Avatar answered Oct 06 '22 22:10

Josh