Ellipsis and ListBox Items
1.) Is there an easy way to trim a string in a listbox, so it doesn't exceed the width of the listbox?
2.) If there is no easy way, I think I have figured out a hard way using the TextRenderer method with a Converter, however I am running into problems figuring out what Font is being used by that itemtemplate textblock.
Sample XAML I am using for my ItemTemplate:
Code:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" Foreground="LightBlue"/>
<TextBlock Text="{Binding Path=Description, Converter={StaticResource ShortenString}, ConverterParameter={StaticResource me}}" FontSize="10" Foreground="White"/>
<TextBlock Text="{Binding Path=Tags, Converter={StaticResource ListToString}}" FontSize="10" Foreground="White"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Re: Ellipsis and ListBox Items
Couldn't you just set the textblock's TextWrap property to Wrap so that the text gets wrapped if its too long? Or does it need to stay on one line
Re: Ellipsis and ListBox Items
Well it could be a whole paragraph worth of text, so I don't want all of that text clogging up my list items.
Re: Ellipsis and ListBox Items
Ah I see, does it need to be neat (as in, the string ends with "..." to show there is more text) or are you not bothered and would settle for it just cutting off? If the latter is true then have you tried setting the ClipToBounds property to True on the element that contains the textblocks?
Re: Ellipsis and ListBox Items
Well as I said, I have a complex way of doing it, but something in my app is not agreeing with it, as when I close it the debugger still things it is running. That is usually a sign of a reference still available.
Here is the code for my valueconverter that has a parameter of the form that is currently running. This is a total hack, but I just wanted to see if it would work:
Code:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string s = (string)value;
Window1 w = (Window1)parameter;
Font f = new Font(w.listBox1.FontFamily.Source, (float) w.listBox1.FontSize);
TextRenderer.MeasureText(s, f, new Size((int)w.listBox1.Width, (int)w.listBox1.Height), TextFormatFlags.ModifyString | TextFormatFlags.EndEllipsis);
Byte[] b = {0};
return s.Split(System.Text.ASCIIEncoding.ASCII.GetChars(b))[0];
}