2010-06-09 56 views
26

我有一个WPF DataGrid绑定到ObservableCollection。 我的收藏中的每件物品都有一个List<someObject>。 在我的行详细信息窗格中,我想为此集合中的每个项目写出格式化的文本块。最终结果将相当于:WPF Repeater(like)控件的收集源?

<TextBlock Style="{StaticResource NBBOTextBlockStyle}" HorizontalAlignment="Right"> 
<TextBlock.Inlines> 
    <Run FontWeight="Bold" Text="{Binding Path=Exchanges[0].Name}" /> 
    <Run FontWeight="Bold" Text="{Binding Path=Exchanges[0].Price}" /> 
    <LineBreak /> 
    <Run Foreground="LightGray" Text="{Binding Path=Exchanges[0].Quantity}" /> 
</TextBlock.Inlines> 
</TextBlock> 
<TextBlock Style="{StaticResource NBBOTextBlockStyle}"> 
<TextBlock.Inlines> 
    <Run FontWeight="Bold" Text="{Binding Path=Exchanges[1].Name}" /> 
    <Run FontWeight="Bold" Text="{Binding Path=Exchanges[1].Price}" /> 
    <LineBreak /> 
    <Run Foreground="LightGray" Text="{Binding Path=Exchanges[1].Quantity}" /> 
</TextBlock.Inlines> 
</TextBlock> 

等等0-n次。

我一直在使用ItemsControl试过这样:

<ItemsControl ItemsSource="{Binding Path=Exchanges}"> 
    <DataTemplate> 
     <Label>test</Label> 
    </DataTemplate> 
</ItemsControl> 

然而,这似乎只是针对多个静态的来源,因为它抛出以下异常(集合创建后不会改变):

ItemsControl操作在ItemsSource正在使用时无效。使用ItemsControl.ItemsSource来访问和修改元素,而不是*

是否有另一种方法来实现这一点?

+0

ItemsControl的应该罚款。当你的ItemsSource被绑定时,你通常在使用ItemsControl的Items属性时会出现这个错误,情况可能如此吗? – 2010-06-09 21:39:32

回答

60

你没有通过指定<DataTemplate .../>ItemsControl里面有什么是您所添加的DataTemplate这种情况下默认的ItemsControl这是Items财产。所以你得到的例外是预期的结果:首先你指定ItemsSource,然后你修改Items。相反,你应该修改ItemTemplate财产上的ItemsControl像这样:

<ItemsControl ItemsSource="{Binding Path=Exchanges}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Label>test</Label> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <StackPanel Orientation="Horizontal"/> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
</ItemsControl> 
+0

真棒,谢谢。无论如何,我可以使模板中的物品水平向上而不是垂直向上? – 2010-06-10 00:26:24

+1

更改ItemsPanel以使用具有方向=“水平”的StackPanel的ItemsPanelTemplate。 – 2010-06-10 01:01:11

+1

编辑:添加约翰建议的示例'ItemPanelTemplate'。如果你想换行,你可以使用'WrapPanel'而不是'StackPanel'。 – repka 2010-06-10 03:55:41