简体   繁体   中英

ItemsControl set ItemSource and get ContentPresenter same time

I have created ItemsControl :

<ItemsControl x:Name="myItemsControl">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock x:Name="myTextBlock" Text="{Binding Name}" Width="75" Height="75" Margin="10" Background="Black" Foreground="White"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

When I set ItemSource and get ContentPresenter same time, it gives me error System.InvalidOperationException: 'This operation is valid only on elements that have this template applied.'

myItemsControl.ItemsSource = new List<Person>() {
    new Person { Name = "1.Name?" },
    new Person { Name = "2.Name?" },
    new Person { Name = "3.Name?" },
    new Person { Name = "4.Name?" },
    new Person { Name = "5.Name?" },
}; ;

for ( int i = 0; i < myItemsControl.Items.Count; i++ ) {
    ContentPresenter contentPresenter = ( ContentPresenter ) myItemsControl.ItemContainerGenerator.ContainerFromItem(myItemsControl.Items[i]);
    TextBlock textBlock = contentPresenter.ContentTemplate.FindName("myTextBlock", contentPresenter) as TextBlock;
}

I know that after the "ItemControl" is fully updated, I need to get the "contentpresser". But I don't know how to do this?

You can access the ContentPresenter in the Loaded event for ItemsControl

<ItemsControl x:Name="myItemsControl" Loaded="myItemsControl_Loaded">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock x:Name="myTextBlock" Text="{Binding Name}" 
                           Width="75" Height="75" Margin="10" Background="Black" Foreground="White"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

Like this

private void myItemsControl_Loaded(object sender, RoutedEventArgs e)
    {
        for (int i = 0; i < myItemsControl.Items.Count; i++)
        {
            ContentPresenter contentPresenter = (ContentPresenter)myItemsControl.ItemContainerGenerator.ContainerFromItem(myItemsControl.Items[i]);
            TextBlock textBlock = contentPresenter.ContentTemplate.FindName("myTextBlock", contentPresenter) as TextBlock;
            textBlock.Text = "Testing";
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM