views:

33

answers:

1

I have an ItemsControl with a DataTemplate that is bound to an ObservableCollection of integers.

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

And in the 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 code, I need to be able to determine the width of the TextBlocks (or whatever the element is if I change it later) in the ItemsControl. Does anyone have an idea how to do this?

When I do DimsContainer.Items[i] it gives me the bound item not the TextBlock.

+2  A: 

You should be able to use instead:

DimsContainer.ItemContainerGenerator.ContainerFromIndex(i);

This won't give you the TextBlock itself, but it will give you the generated ContentPresenter that is wrapped around it by the ItemsControl to contain the ItemTemplate.

John Bowen
And how do I get the width from that?
KrisTrip
Figured it out, thanks!((FrameworkElement)(this.DimsContainer.ItemContainerGenerator.ContainerFromIndex(i))).ActualWidth;
KrisTrip