开发者

Styling dynamically added StackPanel child elements

开发者 https://www.devze.com 2023-01-05 14:08 出处:网络
I have a StackPanel that I dynamically change the contents of every 5 minutes to show the user messages.These messages are displayed as TextBlock or HyperLinkButton.I\'m wondering how/if I can set a s

I have a StackPanel that I dynamically change the contents of every 5 minutes to show the user messages. These messages are displayed as TextBlock or HyperLinkButton. I'm wondering how/if I can set a style within the StackPanels style that will apply to the children.

E.g. I've tried

<Style x:Key="InfoBarStyle" TargetType="StackPanel">
  <Setter Property="TextElement.Foreground" Value="开发者_开发技巧WhiteSmoke"/>
  <Setter Property="TextElement.FontWeight" Value="Bold"/>
</Style>

Is this possible or do I need to set the style in code behind before I add each UiElement?


You can take advantage of Implicit Styling in Silverlight 4.0 as you can in WPF. The trick is to omit the x:Key property when you define a style, and it will automatically get applied to all elements ot the TargetType within the scope of the ResourceDictionary where you define the style.

Here's an example:

 <StackPanel>
  <StackPanel.Resources>
    <Style TargetType="TextBlock">
      <Setter Property="TextElement.Foreground" Value="WhiteSmoke"/>
      <Setter Property="TextElement.FontWeight" Value="Bold"/>
    </Style>
  </StackPanel.Resources>
  <TextBlock Text="My Message"/>
</StackPanel>

All the TextBlock elements inside the StackPanel will now have that style applied however they get added to it.

0

精彩评论

暂无评论...
验证码 换一张
取 消