Item Width in ItemsControl

I have an ItemControl with a DataTemplate that is associated with an ObservableCollection of integers.

<ItemsControl Name="DimsContainer" ItemTemplate="{StaticResource DimensionsTemplate}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
</ItemsControl>

And in Windows Resources:

<Window.Resources>
    <DataTemplate x:Key="DimensionsTemplate" >
        <TextBlock Text="{Binding}"
                       Padding="5"
                       VerticalAlignment="Center"
                       FontSize="32"/>
    </DataTemplate>
</Window.Resources>

My problem is that in the code I need to determine the width of the TextBlocks (or whatever if the item is changed later) in the ItemsControl. Does anyone have an idea how to do this?

When I do DimsContainer.Items [i], it gives me a related item, not a TextBlock.

+3
source share
1 answer

Instead, you can use:

DimsContainer.ItemContainerGenerator.ContainerFromIndex(i);

This will not give you the TextBlock itself, but it will provide you with the created ContentPresenter, which is wrapped around it with an ItemsControl to contain an ItemTemplate.

+4

Source: https://habr.com/ru/post/1760811/


All Articles