简体   繁体   中英

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 UIElement s 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://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.media.visualtreehelper

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM