我试图访问DataTemplate中的Grid,而ItemsControl由ItemsSource绑定.
这是完整的XMAL代码,我如何从外部找到某个元素?
for (int i = 0; i < allViewControl.Items.Count; i++)
{
var container = allViewControl.ItemContainerGenerator.ContainerFromItem(allViewControl.Items[i]) as FrameworkElement;
var grid = allViewControl.ItemTemplate.FindName("grid", container) as DataGrid;
}
我发现这总是返回null?
<ScrollViewer Grid.Row="0" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
<ItemsControl x:Name="allViewControl" Focusable="False" HorizontalContentAlignment="Center"
Grid.IsSharedSizeScope="true" ItemsSource="{Binding AllClassCharacters}"
ItemTemplate="{StaticResource CharacterViewModelTemplate}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Extensions:AnimatedWrapPanel IsItemsHost="true" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
<DataTemplate x:Key="CharacterViewModelTemplate" DataType="{x:Type ViewModel:CharacterViewModel}">
<Grid x:Name="grid" Width="200" Height="Auto" MinHeight="115" Margin="1" MinWidth="130" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" RenderTransformOrigin="0.5,0.5" Background="#66000000" >
<Grid.RowDefinitions>
<RowDefinition Height="70"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ProgressBar x:Name="playerProgressBar" VerticalAlignment="Top" Background="Transparent" Height="5" Width="Auto" Value="0" Visibility="Collapsed" Grid.Column="0" Grid.Row="0" Grid.ColumnSpan ="2" Grid.RowSpan="2" Foreground="White" BorderThickness="0" Style="{DynamicResource ProgressBarStyle1}" />
</Grid>
最佳答案 简短的回答是你不应该这样做 – 使用MVVM应该为你提供更简单的解决方案.
如果你需要它来设置焦点等一些利基案例,那就搜索’find control wpf’ – 有一些现有的问题(example)来破解并从WPF UI树中获取控件