0

Имеется ComboBox со списком шрифтов, первый раз он открывается на выбранном элементе, но после скролла вниз, он открывается в конце списка. При скролле вверх, такого поведения замечено не было. У параметра IsSynchronizedWithCurrentItem установлено значение true. Как каждый раз открывать DropDown лист на выбранном элементе?

Разметка:

<ComboBox x:Name="FontComboBox" IsSynchronizedWithCurrentItem="True"
          xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase"
          ItemTemplate="{DynamicResource FontTemplate}"          
          VirtualizingPanel.IsVirtualizing="True"
          VirtualizingPanel.VirtualizationMode="Recycling"
          SelectionChanged="FontComboBox_SelectionChanged">
    <ComboBox.Resources>
        <CollectionViewSource x:Key="myFonts" Source="{Binding Source={x:Static Fonts.SystemFontFamilies}}">
            <CollectionViewSource.SortDescriptions>
                <ComponentModel:SortDescription PropertyName="Source" />
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
        <Style x:Key="FontStyle">
            <Setter Property="Control.FontFamily" Value="{Binding Source}" />
            <Setter Property="Control.FontSize" Value="14" />
        </Style>
        <DataTemplate x:Key="FontTemplate">
            <StackPanel VirtualizingStackPanel.IsVirtualizing="True">
                <TextBlock Style="{StaticResource FontStyle}" ToolTip="{Binding Source}"
                           Text="{Binding Source}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.Resources>
    <ComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ComboBox.ItemsPanel>
    <ComboBox.ItemsSource>
        <Binding Source="{StaticResource myFonts}" />
    </ComboBox.ItemsSource>
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <EventSetter Event="RequestBringIntoView" Handler="FontComboBox_RequestBringIntoView" />
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

Код:

private void FontComboBox_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
{
    e.Handled = true;
}

введите сюда описание изображения

4

1 ответ 1

1

В обработчик RequestBringIntoView добавил следующее условие:

private void FontComboBox_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e)
{
    if (((ComboBoxItem)e.TargetObject).Content == FontComboBox.SelectedItem)
    {
        return;
    }
    e.Handled = true;
}
1
  • Да, судя по исходникам более нормального способа сделать это нету. 8 июл 2018 в 19:33

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.