Semjon Mössinger
Semjon Mössinger

Reputation: 1890

WPF: How to Set the Width of a ComboBox's DropDown Correctly

I'm about to design a DropDown in WPF using XAML. If my text gets longer than the Width my DropDown element of the ComboBox is larger than the TextBox (as shown by the red arrow). Texts beeing to long are handled by an elllipsis (...).

Any ideas how to correct this?

enter image description here

This is my current XAML code:

<ItemsControl x:Name="ItemsControl"
              ItemsSource="{Binding FilterUiModels}">
    <ItemsControl.ItemTemplate>
        <DataTemplate x:Name="UiModelTemplate">
            <ComboBox x:Name="FilterComboBox"
                      ItemsSource="{Binding AvailableItems}"
                      SelectedItem="{Binding FilterItem}"
                      ScrollViewer.CanContentScroll="False"
                      Width="200">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Width="{Binding ActualWidth, ElementName=FilterComboBox}"
                                   Text="{Binding}" 
                                   TextTrimming="CharacterEllipsis">
                        </TextBlock>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Upvotes: 1

Views: 704

Answers (1)

mm8
mm8

Reputation: 169150

Bind the Width of the Popup to the Width of the ComboBox and set the ScrollViewer.HorizontalScrollBarVisibility attached property to false to hide any horizontal scrollbar:

<ComboBox x:Name="FilterComboBox"
        ItemsSource="{StaticResource localTimeList}"
        SelectedItem="{Binding FilterItem}"
        ScrollViewer.CanContentScroll="False"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled"
        Width="200">
    <ComboBox.Resources>
        <Style TargetType="Popup">
            <Setter Property="Width" Value="{Binding ActualWidth, ElementName=FilterComboBox}"/>
        </Style>
    </ComboBox.Resources>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock  Width="{Binding ActualWidth, ElementName=FilterComboBox}"
                        Text="{Binding}" 
                        TextTrimming="CharacterEllipsis">
            </TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Upvotes: 1

Related Questions