How to display too long text properly in WPF ComboBox

冷暖自知 提交于 2019-12-08 17:05:47

问题


I have a ComboBox that shows text of various lengths. For texts that are not long there is not a problem. For the texts longer than the width of ComboBox I would like to trim the text and add "..." (an ellipsis) at the end to show them properly. The bottom line is that I don't want to change the width of the ComboBox. Does anyone know how to do this?


回答1:


Use a custom ItemTemplate for your ComboBox, which makes use of a TextBlock with the TextTrimming property set to CharacterEllipsis.

Example:

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



回答2:


The answer, as Ross said, is to implement a custom ItemTemplate. However, to make it work properly, you need to do the binding properly.

A note on this method: You cannot set both the DisplayMemberPath and the ItemTemplate, it must be one or the other.

So, for the general case where the display member is the item (such as for a string), you can use binding with no properties to bind to the DataContext of the template:

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

Or, you can put it in a style.

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

For the case where you want to bind to a specific property of the object, similar to how you would use the DisplayMemberPath property, replace the binding with the binding that you would use to a property on the object that you are binding. So, replace the fourth line in my first example with something like this:

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

The binding is in the context of a single item of the type bound to your ComboBox. To make this more explicit, you can do the following:

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

This will give you hints for the properties on the object while you are writing code inside the DataTemplate.




回答3:


You can use TextTrimming CharacterEllipsis or WordEllipsis for the textblocks in your combobox.



来源:https://stackoverflow.com/questions/10549700/how-to-display-too-long-text-properly-in-wpf-combobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!