如何在WP7中的ItemsControl中的特定位置获取UIElement?

时间:2012-01-28 21:15:19

标签: windows-phone-7 windows-phone windows-phone-7.1 uielement

我在icBoard中填充了50个Cell个对象,因此每个Rectangle对象都有Cell作为数据对象。现在,我想根据索引或单元格对象获取相应的Rectangle元素。例如,我想在Rectangle中获取index=15。不是它的数据,而是Rectangle本身。

我怎么能这样做?

        public MainPage()
        {
            InitializeComponent();

            var cells = new List<Cell>();    
            for (int i = 0; i < 50; i++)
            {
                cells.Add(new Cell());
            }    
            icCells.ItemsSource = cells;
        }
       public void sector_Tap(object sender, System.Windows.Input.GestureEventArgs e)
       {
            //some code
            //....
            var tappedRectangle = (sender as Rectangle);
            var spesificRectangle = SOMEHOW_GET_RECTANGLE_AT_POSITION_15;
       }
    <ItemsControl Name="icBoard" Grid.Column="0" Margin="0">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Rectangle  Fill="#501e4696" Width="30" Height="30" Margin="1" Tap="sector_Tap" />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <toolkit:WrapPanel />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>

1 个答案:

答案 0 :(得分:2)

我相信这可行:

ContentPresenter contentPresenter = itemsControl.ItemContainerGenerator.ContainerFromIndex(15) as ContentPresenter;
Rectangle rectangle= FindVisualChild<Rectangle>(contentPresenter );
if (rectangle != null)
{

}

public static T FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                return (T)child;
            }

            T childItem = FindVisualChild<T>(child);
            if (childItem != null) return childItem;
        }
    }
    return null;
}