How to access the ItemsWrapGrid panel which is placed inside the ItemsPanelTemplate?

224 views Asked by At

I used ItemsControl bounded to the ItemsSource collection, and I arranged items using the ItemsWrapGrid control panel. But ItemsWrapGrid panel was placed inside the ItemsPanelTemplate, so I couldn't access that element in the code behind c#.

I have tried with VisualTreeHelper method to find the panel in a visualtree. and doesn't retrieves the element when using inside the items panel template.

<ItemsControl
     x:Name="itemsControl"
     ItemTemplate="{TemplateBinding ItemTemplate}"
     ItemsSource="{TemplateBinding GalleryItemCollection}"
     SelectedItem="{TemplateBinding SelectedItem}">
       <itemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                 <ItemsWrapGrid x:Name="itemsWrapGrid"
                      ItemHeight="{Binding Path=ItemHeight}"
                      ItemWidth="{Binding Path=ItemWidth}"
                      MaximumRowsOrColumns="{Binding Path=MaximumColumnCount}"
                      Orientation="Horizontal" />
             </ItemsPanelTemplate>
       </itemsControl.ItemsPanel>
   </itemsControl>

Can someone please help me how to access the itemswrapGrid code element behind c#?

2

There are 2 answers

2
YanGu On

You could add a Loaded event handler to the ItemsWrapGrid control and assign the sender to a member variable, and then you could access the ItemsWrapGrid control by the member variable.

For example:

//MainPage.xaml
<ItemsWrapGrid x:Name="itemsWrapGrid" Background="Red" Loaded="itemsWrapGrid_Loaded"
                      ……>  </ItemsWrapGrid>


//MainPage.xaml.cs
private ItemsWrapGrid _itemsWrapGrid;

private void itemsWrapGrid_Loaded(object sender, RoutedEventArgs e)
{
    _itemsWrapGrid = sender as ItemsWrapGrid;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    _itemsWrapGrid.Background = new SolidColorBrush(Colors.Blue);
}
1
Павлик Бендер On

In codebehind

(ItemsWrapGrid)itemsControl.ItemsPanelRoot