问题描述
我使用 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);
}