During a recent project, I had the pleasure of dealing with a large and complex WPF form. I do acknowledge that WPF represents a significant step forward from Windows Forms.

For visual appeal, several (> 10) GroupBoxes needed to be colored and bolded uniformly. The code duplicated the same styling logic for each GroupBox. I knew there had to be a better way. I leveraged styles and relative sources to accomplish this goal.

<UserControl.Resources>
	<Style TargetType="{x:Type GroupBox}">
		<Setter Property="HeaderTemplate">
			<Setter.Value>
				<DataTemplate>
					<TextBlock FontWeight="Bold" Foreground="SteelBlue" Text="{Binding Header, RelativeSource={RelativeSource AncestorType=GroupBox}}"/>
				</DataTemplate>
			</Setter.Value>
		</Setter>
	</Style>
</UserControl.Resources>

I am defining a style for all GroupBox’s within the UserControl. The styling is self explanatory. Setting the relative source proved to be slightly more challenging. The above solution provided this functionality and preserved the desired styling. The RelativeSource AncestorType allowed the setting of the header while applying a uniform style, like below.

<GroupBox Header="Optional">
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s