Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8986057
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T21:27:39+00:00 2026-06-15T21:27:39+00:00

I am generating a DataGrid dynamically and adding it to a StackPanel on my

  • 0

I am generating a DataGrid dynamically and adding it to a StackPanel on my WPF application.

As the is dynamically generated, there is no mark up on XAML side for the same and I need to manage the binding and all properties programatically.

I want my DataGrid to have the values in the cell wrapped to the next line if the text is lengthy. I understand that I need to replace the DataGridCell with TextBlock and set the TextWrap property on it. All the examples that I have found suggest something on those lines itself. However, I couldn’t find a way to do it completely from code behind, without XAML.

So far, I have tried to the following code, but it doesn’t work.

DataGrid dg = new DataGrid();   

dg.ItemsSource = ((DataSet)data).Tables[0].DefaultView;
dg.DataContext = ((DataSet)data).Tables[0].DefaultView; 

DataTemplate ct = new DataTemplate(typeof(DataGridCell));
FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
tb.SetValue(TextBlock.TextWrappingProperty, TextWrapping.Wrap);
ct.VisualTree = tb;

dg.ItemTemplate = ct;
dg.ColumnWidth = 300;

Can you please point me to the right direction here?

[Update]: Solution

On further researching I was able to get a solution to my issue. For Auto generated columns, we need to capture the AutoGeneratingColumn event and replace the default DataGridTextColumn by a DataGridTemplateColumn which would have a TextBlock in it. And we can then set the `TextWrappingProperty’ to get the text wrapped.

Following is the updated code:

DataGrid dg = new DataGrid();   

dg.ItemsSource = ((DataSet)data).Tables[0].DefaultView;
dg.DataContext = ((DataSet)data).Tables[0].DefaultView; 

DataTemplate ct = new DataTemplate(typeof(DataGridCell));
FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
tb.SetValue(TextBlock.TextWrappingProperty, TextWrapping.Wrap);
ct.VisualTree = tb;

dg.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(dg_AutoGeneratingColumn);

dg.MaxColumnWidth = 300;

and then the Code under the Event Handler:

 private void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
        //cancel the auto generated column
        e.Cancel = true;

        //Get the existing column
        DataGridTextColumn dgTextC = (DataGridTextColumn)e.Column;

        //Create a new template column 
        DataGridTemplateColumn dgtc = new DataGridTemplateColumn();

        DataTemplate dataTemplate = new DataTemplate(typeof(DataGridCell));

        FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
        tb.SetValue(TextBlock.TextWrappingProperty, TextWrapping.Wrap);
        dataTemplate.VisualTree = tb;

        dgtc.Header = dgTextC.Header;
        dgtc.CellTemplate = dataTemplate;

        tb.SetBinding(TextBlock.TextProperty, dgTextC.Binding);

        //add column back to data grid
        DataGrid dg = sender as DataGrid;
        dg.Columns.Add(dgtc);
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T21:27:40+00:00Added an answer on June 15, 2026 at 9:27 pm

    An alternate approach is to use a behaviour like this.

      public class DataGridWrapTextBehaviour : Behavior<DataGrid>
      {
         private DataGrid DataGrid
         {
            get { return AssociatedObject as DataGrid; }
         }
    
         private Style ElementStyle { get; set; }
         private Style EditingElementStyle { get; set; }
    
         protected override void OnAttached()
         {
            base.OnAttached();
    
            this.ElementStyle = new Style( typeof( TextBlock ) );
            this.ElementStyle.Setters.Add( new Setter( TextBlock.TextWrappingProperty, TextWrapping.Wrap ) );
    
            this.EditingElementStyle = new Style( typeof( TextBox ) );
            this.EditingElementStyle.Setters.Add( new Setter( TextBox.TextWrappingProperty, TextWrapping.Wrap ) );
    
            this.DataGrid.Columns.CollectionChanged += Columns_CollectionChanged;
         }
    
         protected override void OnDetaching()
         {
            this.DataGrid.Columns.CollectionChanged -= Columns_CollectionChanged;
            base.OnDetaching();
         }
    
         private void Columns_CollectionChanged( object sender, NotifyCollectionChangedEventArgs e )
         {
            foreach ( var column in this.DataGrid.Columns.OfType<DataGridTextColumn>() )
            {
               column.ElementStyle = this.ElementStyle;
               column.EditingElementStyle = this.EditingElementStyle;
            }
         }
      }
    

    You can then drap and drop the behaviour onto the DataGrid in Expression Blend.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

So, WPF calls ToString() on objects when generating TextColumns in DataGrid and then i
Here is what is happening: I have a datagrid (which I am generating dynamically)
I have a datagrid with a variable number of columns that I am generating
when generating python wrappers with swig the python wrapper classes in the generated python
For generating PDF from HTML, i need to fill a variable with output from
After generating a type dynamically and calling TypeBuilder.CreateType, I want to create a delegate
I'm trying to create a datagrid with auto generating columns. Let's say my Collection
i am porting my application from windows forms to WPF. I have found that
.Net 4 WPF DataGrid MVVM User clicks add button which triggers command on viewmodel.
Im generating various strings and then I want to save files with generated strings

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.