Добавление счетчика в DataTemplate - PullRequest
0 голосов
/ 19 ноября 2018

У меня есть DataTemplate для ItemsControl, который выводит сетку с некоторыми привязанными элементами управления, и это работает, как и ожидалось.

Однако я хочу, чтобы в первом столбце сетки выводился счетчик каждой созданной сетки.

Например ...

<DataTemplate x:Key="myDataTemplate">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="75" />
            <ColumnDefinition Width="150" />
        </Grid.ColumnDefinitions>

        <TextBlock Text="X" /> <!-- I want a counter to go here -->
        <TextBox Grid.Column="1" Text="{Binding Path=Name}" />
    </Grid>
</DataTemplate>

Я хочу, чтобы первый TextBlock отображал 1, 2, 3, 4 и т. Д., Когда DataTemplate выводит новые сетки.

Есть идеи, как лучше всего это сделать?

Спасибо!

1 Ответ

0 голосов
/ 20 ноября 2018

Вы можете достичь этого, используя AlternationCount и AlternationIndex из ItemsControl. Как,

<ItemsControl ItemsSource="{Binding Items}" AlternationCount="{Binding Items.Count}">
    <ItemsControl.ItemTemplate>
        <DataTemplate x:Key="myDataTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="75" />
                    <ColumnDefinition Width="150" />
                </Grid.ColumnDefinitions>

                <TextBlock Text="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource TemplatedParent}}" />
                <TextBox Grid.Column="1" Text="{Binding Path=Name}" />
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Это даст вам индекс 0; Вы можете использовать IValueConverter, если требуются какие-либо изменения.

...