visc
visc

Reputation: 4959

How do you get UIElements from ItemsControl using a DataTemplate?

I have a StackPanel that was made with a ItemsControl and DataTemplate using an ItemSource of objects.

I know how to get the list of objects from the ItemsControl in the StackPanel: itemsControl.Items

But, now I'd like to get the UIElements associated with these Items.

If we have a StackPanel like this:

<StackPanel x:Name="BrandButtonsStackPanel" Grid.Row="1" HorizontalAlignment="Center">
    <StackPanel.Children>
         <ItemsControl ItemsSource="{x:Bind model:BrandMaintainer.VisibleBrands, Mode=OneWay}">
              <ItemsControl.ItemTemplate>
                  <DataTemplate x:DataType="model:BrandInfo">
                      <Button Tag="{Binding SectionId, Mode=OneWay}" />
                  </DataTemplate>
              </ItemsControl.ItemTemplate>
         </ItemsControl>
    </StackPanel.Children>
</StackPanel>

I tried this method but it's giving me a null value. I can visually see all my buttons generated at runtime:

var brandButton = (Button)itemsControl.ContainerFromItem(itemIndex);

Any ideas? Or is there a better way?

Thanks

EDIT: This states that a FindChildren method exists for UWP. But I'm not seeing it...

https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.media.visualtreehelper

Upvotes: 2

Views: 1300

Answers (2)

HariPrasad kasavajjala
HariPrasad kasavajjala

Reputation: 340

You can use BrandButtonsStackPanel.FindVisualChildren<Button>();

To get all the details of buttons in a list you can use this

List<Button> btnList=BrandButtonsStackPanel.FindVisualChildren<Button>().ToList();

Upvotes: 1

Thomas Flinkow
Thomas Flinkow

Reputation: 5105

I came up with the following extension method

public static IEnumerable<UIElement> GetChildren(this ItemsControl itemsControl)
{
    foreach(var item in itemsControl.Items)
    {
        yield return (UIElement) itemsControl.ItemContainerGenerator.ContainerFromItem(item);
    }
}

which you can then call like this to access your wanted button

var brandButton = (Button) (itemsControl.GetChildren().ToList()[itemIndex]);

I hope it helps you.

Upvotes: 1

Related Questions