ItemsControl同时设置ItemSource和获取ContentPresenter。

问题描述 投票:0回答:1

我已经创建了 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>

当我设置 ItemSource 而得到 ContentPresenter 同时,它给我的错误 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;
}

我知道在 "ItemControl "完全更新后,我需要得到 "contentpresser"。但是我不知道怎么做?

c# wpf itemscontrol contentpresenter
1个回答
0
投票

你可以在ItemsControl的Loaded事件中访问ContentPresenter。

<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>

像这样

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";
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.