Search code examples
wpfdatagrid

Disable Text Wrapping on a Dynamically Filled DataGrid WPF


As the title mentions I am creating a DataGrid as follows:

dataGrid = new DataGrid();
dataGrid.ItemsSource = dSet.Tables[i].DefaultView;

and adding it inside a WrapPanel. Everything is working but I need to disable the text wrapping on rows with multiple lines and limit the column width and having them displaying three dots.

I tried styling the DataGridCell but nothing is working for me.

Can anyone help with this?

Note: I cannot create predefined columns since this is a dynamic grid that I cannot determine before what columns it will populate.


Solution

  • You could handle the AutoGeneratingColumn event and use a converter that converts the long string to a shorter one:

    dataGrid = new DataGrid();
    dataGrid.ItemsSource = dSet.Tables[i].DefaultView;
    LongTextConverter LongTextConverter = new LongTextConverter();
    dataGrid.AutoGeneratingColumn += (ss, ee) => 
    {
        DataGridTextColumn column = ee.Column as DataGridTextColumn;
        column.Binding = new Binding(ee.PropertyName) { Converter = LongTextConverter };
    };
    

    LongTextConverter.cs:

    public class LongTextConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string s = value as string;
            if (!string.IsNullOrEmpty(s) && s.Length > 10)
                return $"{s.Substring(0, 7)}...";
    
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }