0

I filled the icBoard with 50 Cell objects, so each Rectangle object has Cell as data object. Now, I want according to index or cell object to get the corresponding Rectangle element. For example I want to get the Rectangle in index=15. Not it's data but the Rectangle itself.

How I can do this?

        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>
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
theateist
  • 13,879
  • 17
  • 69
  • 109

1 Answers1

2

I believe this might work:

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;
}
MyKuLLSKI
  • 5,285
  • 3
  • 20
  • 39
  • it fails on this row `VisualTreeHelper.GetChild(itemPresenter, 15);`. I've change 15 to 0 and no error raised, but it didn't return Rectangle. This `((WrapPanel)dependencyObject).Children` returns all elements(50), but I cannot cast it Rectangle. So what **children** property is? – theateist Jan 28 '12 at 22:47