Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

c# - WPF Repeater (like) control for collection source?

I have a WPF DataGrid bound to ObservableCollection. Each item in my collection has Property which is a List<someObject>. In my row details pane, I would like to write out formatted text blocks for each item in this collection. The end result would be something equivalent to:

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

and so on 0-n times.

I've tried using ItemsControl for this:

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

however, this appears to be only meant for more static sources, as it throws the following exception (collection is not altered after creation):

ItemsControl Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead*

Is there another way to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you did by specifying <DataTemplate .../> inside of ItemsControl is you added this instance of DataTemplate to default property of ItemsControl which is Items. So the exception you got is the expected result: first you specify the ItemsSource, then you modify Items. Instead you should modify ItemTemplate property on your ItemsControl like so:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...