Сгруппированное поле со списком WPF прокручивает группы, а не элементы

Мы пытаемся реализовать простую группировку элементов в ComboBox с помощью ICollectionView. Группировка и сортировка, используемые в CollectionView, работают правильно. Но список всплывающих элементов, созданный ComboBox, не работает должным образом, поскольку полоса прокрутки прокручивает группы, а не элементы.

например: если бы было 2 группы по 25 элементов, полоса прокрутки имела бы две позиции/точки для прокрутки, а не желаемые 50.

Может ли кто-нибудь объяснить, почему полоса прокрутки прокручивает группы, а не элементы внутри групп, и как мы можем изменить это поведение?

Модель представления, устанавливающая ICollectionView:

public ViewModel()
{

CurrenciesView.Filter = CurrencyFilter;
CurrenciesView.SortDescriptions.Add(new SortDescription("MajorCurrency", ListSortDirection.Descending));
CurrenciesView.SortDescriptions.Add(new SortDescription("Code", ListSortDirection.Ascending));
CurrenciesView.GroupDescriptions.Add(new PropertyGroupDescription("MajorCurrency", new CurrencyGroupConverter()));


public ICollectionView CurrenciesView { get { return CollectionViewSource.GetDefaultView(currencies); } }
    private ObservableCollection<Currency> currencies = new ObservableCollection<Currency>();
public ObservableCollection<Currency> Currencies
{
    get { return this.currencies; }
    set
    {
        if (this.currencies != value)
        {
            this.currencies = value;
            this.PropertyChanged(this, new PropertyChangedEventArgs("Currencies"));
        }
    }
}

XAML UserControl, на котором размещен ComboBox

<UserControl x:Class="FilterView"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:vm="clr-namespace:ViewModels">
<UserControl.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="CurrencyItem">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Code}" FontWeight="ExtraBold"/>
                <TextBlock Text="{Binding Description}" Margin="10,0,0,0"/>
            </StackPanel>
        </DataTemplate>
        <Style TargetType="ComboBox">
            <Setter Property="MinWidth" Value="100"/>
            <Setter Property="Margin" Value="0,5,0,5"/>
        </Style>
        <DataTemplate x:Key="GroupHeader">
            <TextBlock Text="{Binding Name}" Padding="3"/>
        </DataTemplate>
    </ResourceDictionary>
</UserControl.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Label Grid.Column="0" Grid.Row="0">Currency</Label>
    <ComboBox Grid.Column="1" Grid.Row="0" Name="Currency"
                        ItemsSource="{Binding Path=CurrenciesView, Mode=OneWay}"
                        ItemTemplate="{StaticResource CurrencyItem}"
                        SelectedValuePath="Code"
                        IsSynchronizedWithCurrentItem="True">
        <ComboBox.GroupStyle>
            <GroupStyle HeaderTemplate="{StaticResource GroupHeader}"/>
        </ComboBox.GroupStyle>
    </ComboBox>
</Grid>
</UserControl>

Прокрутите первую позицию

Вторая позиция прокрутки


person MW_dev    schedule 10.07.2013    source источник


Ответы (2)


Исправлено установкой CanContentScroll = false в шаблоне PART_Popup для дочернего ScrollViewer.

<UserControl x:Class="FilterView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:ViewModels">
  <UserControl.Resources>
    <ResourceDictionary>
      <DataTemplate x:Key="CurrencyItem">
        <StackPanel Orientation="Horizontal">
          <TextBlock Text="{Binding Code}" FontWeight="ExtraBold"/>
          <TextBlock Text="{Binding Description}" Margin="10,0,0,0"/>
        </StackPanel>
      </DataTemplate>
      <Style TargetType="ComboBox">
        <Setter Property="MinWidth" Value="100"/>
        <Setter Property="Margin" Value="0,5,0,5"/>
      </Style>
      <DataTemplate x:Key="GroupHeader">
        <TextBlock Text="{Binding Name}" Padding="3"/>
      </DataTemplate>
    </ResourceDictionary>
  </UserControl.Resources>
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto"/>
      <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Label Grid.Column="0" Grid.Row="0">Currency</Label>
    <ComboBox Grid.Column="1" Grid.Row="0" Name="Currency"
              ItemsSource="{Binding Path=CurrenciesView, Mode=OneWay}"
              ItemTemplate="{StaticResource CurrencyItem}"
              SelectedValuePath="Code"
              IsSynchronizedWithCurrentItem="True"
              **ScrollViewer.HorizontalScrollBarVisibility="Auto"
              ScrollViewer.VerticalScrollBarVisibility="Auto"
              ScrollViewer.CanContentScroll="True"**>
      <ComboBox.GroupStyle>
        <GroupStyle HeaderTemplate="{StaticResource GroupHeader}"/>
      </ComboBox.GroupStyle>
    </ComboBox>
  </Grid>
</UserControl>

Или в производном элементе управления ComboBox:

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        Popup popup = GetTemplateChild("PART_Popup") as Popup;
        if (popup != null)
        {
            ScrollViewer scrollViewer = GetVisualChild<ScrollViewer>(popup.Child);
            if (scrollViewer != null)
            {
                scrollViewer.CanContentScroll = false;
            }
        }
    }
person MW_dev    schedule 06.10.2013
comment
не могли бы вы дать фрагмент кода, как вы решили проблему, я не понимаю, где установить CanContentScroll = false. - person bolia; 14.03.2014
comment
@bolia Немного сложно дать фрагмент кода, но я попытаюсь обновить исходный код выше. - person MW_dev; 17.03.2014

<Combobox ScrollViewer.CanContentScroll="False"></Combobox>

Используйте приведенный выше код, это решит проблему.

С уважением, Ратиканта.

person ratikanta rout    schedule 28.09.2016
comment
Привет, ‹Combobox ScrollViewer.CanContentScroll=False›‹/Combobox› Используйте приведенный выше код, чтобы решить проблему. - person ratikanta rout; 28.09.2016
comment
Это то же решение, предложенное в другом ответе, который является более старым, одобренным, принятым и более подробным. - person lfurini; 28.09.2016
comment
Привет, они подают заявку на шаблон PART_PopUp, который я использовал на родительском уровне со списком. - person ratikanta rout; 03.10.2016