【问题标题】:WPF Repeater (like) control for collection source?收集源的 WPF 中继器(类似)控件?
【发布时间】:2010-06-09 21:35:21
【问题描述】:

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

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

但是,这似乎仅适用于更多静态源,因为它会引发以下异常(集合在创建后不会更改):

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

还有其他方法可以实现吗?

【问题讨论】:

  • ItemsControl 应该没问题。在绑定 ItemsSource 的情况下使用 ItemsControl 的 Items 属性时,通常会出现此错误,可能是这种情况吗?

标签: c# .net wpf


【解决方案1】:

您通过在ItemsControl 中指定&lt;DataTemplate .../&gt; 所做的是将DataTemplate 的这个实例添加到ItemsControl 的默认属性Items。所以你得到的例外是预期的结果:首先你指定ItemsSource,然后你修改Items。相反,您应该像这样修改ItemsControl 上的ItemTemplate 属性:

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

【讨论】:

  • 太棒了,谢谢。无论如何,我可以使该模板中的项目水平而不是垂直堆叠?
  • 更改 ItemsPanel 以将 ItemsPanelTemplate 与具有 Orientation="Horizo​​ntal" 的 StackPanel 一起使用。
  • 编辑:添加了 John 建议的示例 ItemPanelTemplate。如果你想要换行,你可以使用WrapPanel 而不是StackPanel
猜你喜欢
  • 1970-01-01
  • 2017-11-14
  • 1970-01-01
  • 1970-01-01
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
相关资源
最近更新 更多