我使用ItemsControl绑定到ItemsSource集合,并且我使用ItemsWrapGrid来安排项目控制面板。但是ItemsWrapGrid面板被放置在ItemsPanelTemplate中,所以我无法在c#后面的代码中访问该元素。
我已经尝试了VisualTreeHelper方法在可视化树中查找面板。并且在items面板模板中使用时不检索元素。
<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>
有人能告诉我如何访问itemswrapGridc#背后的代码元素?
您可以将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);
}