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

问题描述

我使用 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 代码元素吗?

解决方法

您可以向 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);
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...