0

I'm working in VB.Net w/ WPF and I need to create a DataGrid at run-time (in the code-behind) with the text in each grid cell able to wrap. I've found a lot of examples showing how to do this in the XML but I can't find anything explaining how this is done in the code-behind. I'm stuck trying to figure out how the DataGridTemplateColumn, CellTemplate, and DataTemplate all work together. Any help on this would be greatly appreciated.

I think this is equivalent to what I'm trying to do:

<DataGridTemplateColumn>
 <DataGridTemplateColumn.CellTemplate>
  <DataTemplate>
   <TextBlock TextWrapping="Wrap" />
  </DataTemplate>
 </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Update:

I've made some progress but the cell text wrapping is still not working... Here is what I've got so far:

Dim grid As New DataGrid
grid.AutoGenerateColumns = False

Dim dgtc As New DataGridTemplateColumn
dgtc.Header = "Test"
dgtc.Width = 200

Dim factory1 As New FrameworkElementFactory(GetType(TextBlock))

Dim b1 As New Binding("WrapDirection.Right")

factory1.SetValue(TextBlock.TextWrappingProperty, b1)

Dim dt As New DataTemplate

dt.VisualTree = factory1

dgtc.CellTemplate = dt

grid.Columns.Add(dgtc)

I think the problem is with the binding and the textblock property. Something like this would make more sense but it doesn't work...

Dim b1 As New Binding("Wrap")

factory1.SetValue(TextBlock.TextWrapping, b1)
zzMzz
  • 467
  • 1
  • 5
  • 21
  • I found this article: What is the code behind for datagridtemplatecolumn, and how to use it? http://stackoverflow.com/questions/1754608/what-is-the-code-behind-for-datagridtemplatecolumn-and-how-to-use-it Unfortunately I'm still having trouble understanding how to get this to work with the DataGrid cell's textblock. – zzMzz May 31 '12 at 14:49

1 Answers1

2

So I finally was able to tack down what I was looking for: http://social.msdn.microsoft.com/Forums/br/wpf/thread/bf75f61a-6247-4964-95be-7ea6f0fa0998

Using that as a reference I was finally able to get some code working:

Dim grid As New DataGrid
grid.AutoGenerateColumns = False

Dim dgtextcol As New DataGridTextColumn
dgtextcol.Width = 200

dgtextcol.Header = "Test"

Dim b1 = New Binding("Message")
b1.Mode = BindingMode.OneWay

dgtextcol.Binding = b1

Dim textStyle = New Style(GetType(TextBlock))
textStyle.Setters.Add(New Setter(TextBlock.TextWrappingProperty, TextWrapping.Wrap))

dgtextcol.ElementStyle = textStyle

grid.Columns.Add(dgtextcol)
zzMzz
  • 467
  • 1
  • 5
  • 21