如何从代码中访问ItemControls ItemTemplate中由DataTemplate创建的控件?

时间:2017-12-03 18:59:06

标签: c# wpf xaml controls datatemplate

要重现,请确保包含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个对象?

0 个答案:

没有答案