Search code examples
c#wpfxamltexttrimming

WPF ComboBox text trimming


I want to show "..." at the end of the ComboBox content when its text is to large. I tried this but it doesn't work:

<!--this is App.xaml file-->

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

How my ComboBox looks

How it should look

What am I doing wrong?

EDIT: This is how I add items to ComboBox:

SqlDataAdapter adpt = new SqlDataAdapter();
DataTable tbl = new DataTable();
        
adpt.SelectCommand = new SqlCommand("SELECT * FROM foo", conn);
adpt.Fill(tbl);
comboBox1.Items.Add("");
foreach (DataRow row in tbl.Rows)
{
            ComboBoxItem item = new ComboBoxItem();
            item.Content = row["title"].ToString();
            item.Tag = row["id"].ToString();
            comboBox1.Items.Add(item);
}
tbl.Clear();

Solution

  • I think you have to add a Item-DataTemplate that contains a Textblock which again has the TextTrimming property. So add this ItemTempalte to your ComboBox1 in the corresponding xaml

    <ComboBox>
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock
                  Text="{TemplateBinding Content}"
                  TextTrimming="CharacterEllipsis"
                />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>