2011-03-02 78 views
0

例如,下面是一些代码来填充列表框2个列表框:Silverlight:如何在资源控件中设置控件的样式?

<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> 

内部列表框同时出现在垂直列表中显示其内容。现在,我知道如何让单个列表框水平显示其内容,并且我知道如何通过在资源中设置样式来完成此操作。我无法弄清楚的是如何将其设置为一次只能应用于外部列表框的资源,而不是每次添加另一个内部列表框(即将其应用于每个内部列表框)。

这是我无数次失败的尝试:

<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> 
        </ListBox.ItemTemplate> 
       </ListBox> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</UserControl.Resources> 

如果我还没有明确表态,我想看看我的列表框是11,12并排侧第一排和21 ,并排排列在第二排。

+0

将有办法做到这一点使用'ItemTemplate'但是你真的确定要这个接口?你真的需要一个可选列表项目的可选列表吗?我注意到ListBox经常被用于布局目的,这很好,但并不总是最好的选择。明确说明为什么要使用ListBox来说明一个简单的StackPanels和/或具有ScrollViewer的ItemsControl。如果你描述你的目标,而不是你选择实现我们目前未知的目标,或许这将是一件好事。 – AnthonyWJones 2011-03-02 20:09:10

+0

目前我有4个列表框,其中2个包含颜色,另外2个包含图像位。所有列表框都从集合中填充。而不是4个列表框,它将更加整洁地在代码中填充4个列表框,并将它们添加到用户界面上的1列表框中。 – descf 2011-03-02 20:32:42

回答

0

如果您使用Silverlight 4,则可以创建隐式样式。您可以通过在样式声明中不包含Key来完成此操作。这将隐式地将该样式应用于该资源范围内的所有控件。然后,您还需要显式设置根列表框的ItemsPanel以垂直布局。

<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> 
+0

我不太清楚这是如何适用于我的问题? – descf 2011-03-02 16:09:42

+0

为了更具体一点,用于设置我发布的样式的XAML代码不起作用 - 这就是问题所在 - 并且我不希望以同样的方式隐式设置所有外部或内部列表框的样式。 – descf 2011-03-02 16:29:36

+0

对不起,只是意识到你的XAMl是错的。定影。 您可以在外部列表框的资源中创建一个隐式样式。这样每个内部列表框都会隐式地获取该样式。这应该可以解决您不需要在每个内部ListBox上明确设置样式的问题。 – 2011-03-02 17:13:31

相关问题