In <Window.Resources> I have defined following style:
<Style x:Key='textBlockStyle' TargetType='TextBlock'> <Setter Property='Margin' Value='5,0,5,0'/> </Style>
I have defined some grid where I have four TextBlocks:
<WrapPanel> <TextBlock Style='{StaticResource textBlockStyle}'>Server</TextBlock> <TextBlock Style='{StaticResource textBlockStyle}'>IP</TextBlock> <TextBlock Style='{StaticResource textBlockStyle}'>Port</TextBlock> <TextBlock Style='{StaticResource textBlockStyle}'>Status</TextBlock> </WrapPanel>
Problem: I need to reference the textBlockStyle four times.
Question: Is it possible to set that style just once at in WrapPanel or somewhere else without repeating the reference to the style?
Maybe something like:
<WrapPanel Style='{StaticResource textBlockStyle}'> <TextBlock>Server</TextBlock> <TextBlock>IP</TextBlock> <TextBlock>Port</TextBlock> <TextBlock>Status</TextBlock> </WrapPanel>
I am not searching for a global solution! I could delete that x:Key='textBlockStyle' property, but that would affect all TextBlocks in the Window. I need a more selective mechanism, but without that ugly code duplication.
You have several options, presented here in order of how well they scale.
Option 1: Define the Style without a key at a lower level
You can stick the resource at the
WrapPanellevel so that it only affects controls inside thatWrapPanel:Notice the lack of key. This
Stylewill apply to allTextBlocks within theWrapPanel.Option 2: Define the Style with a key and again without at a lower level
If you define the
Styleat a higher level with a key, you can then define anotherStyleat a lower level without a key, and base thatStyleon the higher level one:This results in a
Stylebeing automatically applied toTextBlocks inside theWrapPanel, but not outside it. Also, you don’t duplicate the details of theStyle– they are stored at a higher level.Option 3: Place the Styles in a ResourceDictionary and selectively merge it
Finally, you can place your
Styles in a separateResourceDictionaryand selectively merge that dictionary into a control’sResourcescollection:Now you can have as many style sets defined in separate dictionaries as you like, and then selectively apply them to your element tree.