WPF:默认情况下为自定义 ComboBox 启用虚拟化

WPF : Enable virtualization by default for a custom ComboBox

我做了一个继承自 ComboBox 的自定义 ComboBox

我想为我的自定义 ComboBox.

默认启用虚拟化

我曾考虑在 ComboBox 构造函数中执行此操作,但我不知道是否可行。 这将使我避免每次都必须添加以下代码。

<CustomComboBox>
    <CustomComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </CustomComboBox.ItemsPanel>
</CustomComboBox>

你知道我该怎么做吗?

您可以创建一个 Style 并将其添加到所需范围内的 ResourceDictionary

App.xaml

<Style TargetType="ComboBox">
  <Setter Property="ItemsPanel">
    <Setter.Value>
      <ItemsPanelTemplate>
        <VirtualizingStackPanel />
      </ItemsPanelTemplate>
    </Setter.Value>
  </Setter>
</Style>

或者,扩展 ComboBox 并硬编码 Panel:

public class VirtualizingComboBox : ComboBox
{
  public override void OnApplyTemplate()
  {
    base.OnApplyTemplate();
    string itemsPanelTemplateText = @"
      <ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
        <VirtualizingStackPanel />
      </ItemsPanelTemplate>";

    ItemsPanelTemplate temsPanelTemplate = System.Windows.Markup.XamlReader.Parse(itemsPanelTemplateText) as ItemsPanelTemplate;
    this.ItemsPanel = temsPanelTemplate ;
  }
}