Silverlight: How do I set the style of a control within a control in a resource?
For example, here is some code to populate a listbox with 2 listboxes:
<ListBox x:Name="LayoutRoot" Width="200" Height="400" Style="{StaticResource ListStyle}" >
<ListBoxItem>
<ListBox>
<ListBoxItem>11</ListBoxItem>
<ListBoxItem>12</ListBoxItem>
</ListBox>
</ListBoxItem>
<ListBoxItem>
<ListBox>
<ListBoxItem>21</ListBoxItem>
<ListBoxItem>22</ListBoxItem>
</ListBox>
</ListBoxItem>
</ListBox>
The inner list boxes both appear displaying their content in a vertical list. Now, I know how to get a single list box to display its content horizontally, and I know how to do this by setting the style in a resource. What I can't figure out is how to set it in a resource that I can just apply once to the outer listbox and not every time I add another inner listbox (i.e. apply it to each and every inner listbox).
Here is my umpteenth failed attempt:
<UserControl.Resources>
<Style x:Key="ListStyle" TargetType="ListBox">
<Setter Property="Template">
<Setter.Value>
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<ListBox>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</DataTemplate>
&开发者_如何学Golt;/ListBox.ItemTemplate>
</ListBox>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
If I haven't made it clear, what I want to see in my listbox is 11, 12 side-by-side in the first row and 21, 22 side-by-side in the second row.
If you're using Silverlight 4, you can create an implicit style. You do this by not including a Key in the Style declaration. This will implicitly apply the style to all of the controls within the scope of that resource. You then need to also explicitly set the ItemsPanel of the Root ListBox to layout Vertically.
<ListBox x:Name="LayoutRoot" Width="200" Height="400">
<ListBox.Resources>
<Style TargetType="ListBox">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<toolkit:WrapPanel/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBoxItem>
<ListBox>
<ListBoxItem>11</ListBoxItem>
<ListBoxItem>12</ListBoxItem>
</ListBox>
</ListBoxItem>
<ListBoxItem>
<ListBox>
<ListBoxItem>21</ListBoxItem>
<ListBoxItem>22</ListBoxItem>
</ListBox>
</ListBoxItem>
</ListBox>
精彩评论