How to display too long text in WPF ComboBox

I have a ComboBox that shows text of different lengths. For texts that are not long, there are no problems. For texts longer than the width of the ComboBox, I would like to crop the text and add a “...” (ellipsis) at the end to show them correctly. The bottom line is that I do not want to change the width of the ComboBox. Does anyone know how to do this?

+5
source share
3 answers

Use a ItemTemplatecustom ItemTemplateone that uses TextBlockwith the property TextTrimmingset to CharacterEllipsis.

Example:

<ComboBox ItemsSource="..." SelectedValuePath="...">
  <ComboBox.ItemTemplate>
    <DataTemplate>
      <TextBlock 
        Text="{Binding ...}" 
        TextTrimming="CharacterEllipsis" />
    </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>
+11
source

You can use TextTrimming CharacterEllipsis or WordEllipsisfor text blocks in your combo box.

0

, , ItemTemplate. , , .

: DisplayMemberPath, ItemTemplate, .

, , (, ), - DataContext :

<ComboBox ItemsSource="..." SelectedValuePath="...">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding }" TextTrimming="CharacterEllipsis" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

.

<Style TargetType="{x:Type ComboBox}">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock Text="{Binding }" TextTrimming="CharacterEllipsis" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

, , , DisplayMemberPath, , , . , :

<TextBlock Text="{Binding MyDisplayMemberProperty}" TextTrimming="CharacterEllipsis" />

, ComboBox. , :

<DataTemplate DataType="{x:Type namespace:MyItemType}">
    <!-- My DataTemplate stuff here -->
</DataTemplate>

This will give you hints for object properties when you write code inside DataTemplate.

0
source

All Articles