为什么ContentPresenter的渲染时间大于其子级的渲染时间?

问题描述

请参见下图:

ContentPresenter's render time is bigger than others

我只是在VS2017中使用Performance Profiler,我发现listBoxItem的ContentPresenter渲染时间比其子级的渲染时间长。

我必须减少总渲染时间(大约为1.1秒)。 ListBoxItems呈现时间的总和也是1.1s。

我不知道为什么会时差。

列表框的可视树如下:

  • 列表框(3057)
    • 边界(3056)
      • ScollViewer(3055)
        • 网格(3054)
          • ScrollContentPresenter(3031)
            • ItemsPresenter(3029)
              • VirtualizingStackPanel(3028)
                • ListBoxItem(120)
                • ListBoxItem(84)...

解决方法

我可以减少视觉树的控制。

我的方法是“重新定义某些控件的ControlTemplate”

在重新定义ControlTemplate之前,我的ListBoxItem具有Bd(Border),ContentPresenter,Grid等,如下所示 Visual Tree

像xaml一样重新定义ControlTemplate之后

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <ContentPresenter>
                         <ContentPresenter.Style>
                             <Style TargetType="{x:Type ContentPresenter}">
                                 <Setter Property="VirtualizingPanel.IsVirtualizing" Value="True"/>
                                 <Setter Property="VirtualizingPanel.VirtualizationMode" Value="Recycling"/>
                              </Style>
                          </ContentPresenter.Style>
                      </ContentPresenter>
                  </ControlTemplate>
              </Setter.Value>
          </Setter>
      </Style>
  </ListBox.ItemContainerStyle>

然后我可以删除“ Bd”(边框),如下所示。

  • ListBoxItem
    • ContentPresenter
      • 网格...

为减少渲染时间,我将找到无用的控件并将其删除。