要重现,请确保包含System.Windows.Interactivity
引用。
鉴于以下内容 -
<Window
x:Class="Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:l="clr-namespace:Example" mc:Ignorable="d"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:lib="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<ItemsControl ItemsSource="{x:Static l:App.ItemsSource}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid>
<i:Interaction.Behaviors>
<l:PanelObserver />
</i:Interaction.Behaviors>
</UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
由以下类支持 -
public partial class App : Application {
private static readonly string[] _itemsSource = new string[]{
"This", "Is", "An", "Example"
};
public static string[ ] ItemsSource => _itemsSource;
}
public class PanelObserver : Behavior<Panel> {
protected override void OnAttached( ) {
this.AssociatedObject.Loaded += new RoutedEventHandler( _Loaded );
void _Loaded( object sender, RoutedEventArgs e ) {
UIElementCollection children = ( sender as Panel )?.Children;
//So how can I resolve the children ( which is many ContentPresenters )
//into text blocks?
}
}
}
在行为OnAttached
方法中,加载控件时会调用Loaded
事件处理程序。
UIElementCollection
包含许多ContentPresenter
个对象......
如何/何时可以访问TextBlock
中应包含的UniformGrid
个对象?