ItemsControl中项的宽度

3
我有一个ItemsControl,其DataTemplate绑定到一个整数类型的ObservableCollection。
<ItemsControl Name="DimsContainer" ItemTemplate="{StaticResource DimensionsTemplate}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
</ItemsControl>

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

我的问题是,在代码中,我需要能够确定ItemsControl中TextBlocks(或者如果以后更改了元素,就是任何元素)的宽度。 有人有想法如何做到这一点吗?

当我使用DimsContainer.Items[i]时,它给出绑定的项而不是TextBlock。

1个回答

4

您可以使用以下方式代替:

DimsContainer.ItemContainerGenerator.ContainerFromIndex(i);

这不会直接给你TextBlock本身,但它会给你由ItemsControl生成的ContentPresenter,该ContentPresenter用于包含ItemTemplate。

那么我该如何从中获取宽度? - KrisTrip
2
搞定了,谢谢! ((FrameworkElement)(this.DimsContainer.ItemContainerGenerator.ContainerFromIndex(i))).ActualWidth; - KrisTrip

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接