Ellipsis text in the DataGridColumn

Jun 24, 2009 at 10:49 AM

Hi all,

I want to implement an DataGridColumn which can auto show the ellipsis text if content is beyond the width of the column. I use TextBlock in the DataGridTemplateColum, I know TextBlock have a property TextTrimming="CharacterEllipsis", but I need use the ellipsis in the middle of the string. Since the content is a path of file. It needs show the filename and the driver, so anyone has the expierience on that please give me some suggestion? And when drag the column and extend the width of the column, it needs also extend the strings to show?

Thanks very much


Jun 25, 2009 at 12:20 PM
Edited Jun 25, 2009 at 12:23 PM

Here I use DataBinding and ValueConverter to do it, it can somehow work for English text, but in case the other unicode text, for example Chinese, it will have the problem, and looks the Converter will not be called. Anyone know the reason and solution, thanks very much.

                            <TextBlock Name="txtOutput" HorizontalAlignment="Stretch" TextAlignment="Justify" ToolTip="{Binding Path=Output}">
                                    <MultiBinding Converter="{StaticResource OutputToEllipsisDisplayConverter}" ConverterParameter="FontSize">
                                        <Binding Path="Output"/>
                                        <Binding Path="ActualWidth" ElementName="txtOutput"/>
                                        <Binding Path="FontSize" ElementName="txtOutput"/>
    public class OutputToEllipsisDisplayConverter : IMultiValueConverter
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
            const String Ellipsis = /*MSG0*/@"...\";

            String displayText = String.Empty;
            String path = values[0] as String;

            if (String.IsNullOrEmpty(path)) 
                return displayText;

            double actualWidth = (double)values[1];
            double fontSize = (double)values[2];
            int charCapacity = (int)((actualWidth) / (fontSize/2));
            string prefix = Path.GetDirectoryName(path) + "\\";
            String filename = Path.GetFileName(path);

            int leftCharNum = 0;
            if (charCapacity >= path.Length)
                displayText = path;
            else if (charCapacity >= Ellipsis.Length + filename.Length)
                leftCharNum = charCapacity - filename.Length - Ellipsis.Length;
                string subPrefix = prefix.Substring(0, leftCharNum);
                displayText = subPrefix + Ellipsis + filename;
                displayText = path;
            return displayText;

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            throw new NotSupportedException();