如何访问位于 ItemsPanelTemplate 内的 ItemsWrapGrid 面板?

问题描述 投票:0回答:2

我使用了 ItemsControl 绑定到 ItemsSource 集合,并使用 ItemsWrapGrid 控制面板来排列项目。但 ItemsWrapGrid 面板放置在 ItemsPanelTemplate 内部,因此我无法在 c# 后面的代码中访问该元素。

我尝试使用 VisualTreeHelper 方法在视觉树中查找面板。并且在项目面板模板内部使用时不会检索元素。

<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>

有人可以帮助我如何访问 c# 后面的 itemswrapGrid 代码元素吗?

c# uwp itemscontrol itemspaneltemplate winui-3
2个回答
1
投票

您可以向

Loaded
控件添加
ItemsWrapGrid
事件处理程序,并将发送者分配给成员变量,然后您可以通过该成员变量访问
ItemsWrapGrid
控件。

例如:

//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);
}

0
投票

在代码隐藏中

(ItemsWrapGrid)itemsControl.ItemsPanelRoot
© www.soinside.com 2019 - 2024. All rights reserved.