Home > OS >  WPF : Enable virtualization by default for a custom ComboBox
WPF : Enable virtualization by default for a custom ComboBox

Time:05-24

I made a custom ComboBox that inherits from ComboBox.

I would like enable the virtualization by default for my custom ComboBox.

I was thinking of doing it in the ComboBox constructor but I don't know if it's possible. This would allow me to avoid having to add the following code every time.

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

Do you have any idea how I can do this?

CodePudding user response:

You can create a Style and add it to a ResourceDictionary within the required scope:

App.xaml

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

Alternatively, extend ComboBox and hardcode the 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 ;
  }
}
  • Related