I have a really disturbing issue with .NET 4.0 DataGrid. I have proportional template columns containing TextBlock with textWrapping enabled.
Problem is, the height of the DataGrid is not correct at load time (it’s sized as if the textblock were all wrapped at their maximum.) and does not update their size when resizing. It appears to be a layout issue (MeasureOverride and ArrangeOverride seems to be called when proportional sizes are not resolved, and not called afterwards…) but I haven’t been able to solve it.
Here is a simplified code that shows the issue :
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="700" Width="525">
<StackPanel Width="500">
<Button Content="Add DataGrid" Click="Button_Click" />
<ItemsControl x:Name="itemsControl">
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Control.Margin" Value="5" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</StackPanel>
MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace WpfApplication1
{
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
itemsControl.Items.Add(CreateDataGrid());
}
private DataGrid CreateDataGrid()
{
var dataGrid = new DataGrid() { HeadersVisibility = DataGridHeadersVisibility.Column };
dataGrid.MaxWidth = 500;
dataGrid.Background = Brushes.LightSteelBlue;
dataGrid.Columns.Add(GetDataGridTemplateColumn("Label", "Auto"));
dataGrid.Columns.Add(GetDataGridTemplateColumn("Value", "*"));
dataGrid.Items.Add(new Entry() { Label = "Text Example 1", Value = "Some wrapped text" });
dataGrid.Items.Add(new Entry() { Label = "Text Example 2", Value = "Some wrapped text" });
return dataGrid;
}
private DataGridTemplateColumn GetDataGridTemplateColumn(string bindingPath, string columnWidth)
{
DataGridTemplateColumn result = new DataGridTemplateColumn() { Width = (DataGridLength)(converter.ConvertFrom(columnWidth))};
FrameworkElementFactory cellTemplateframeworkElementFactory = new FrameworkElementFactory(typeof(TextBox));
cellTemplateframeworkElementFactory.SetValue(TextBox.NameProperty, "cellContentControl");
cellTemplateframeworkElementFactory.SetValue(TextBox.TextProperty, new Binding(bindingPath));
cellTemplateframeworkElementFactory.SetValue(TextBox.TextWrappingProperty, TextWrapping.Wrap);
result.CellTemplate = new DataTemplate() { VisualTree = cellTemplateframeworkElementFactory };
return result;
}
private static DataGridLengthConverter converter = new DataGridLengthConverter();
}
public class Entry
{
public string Label { get; set; }
public string Value { get; set; }
}
}


Finally found a solution : setting CanContentScroll to false on the DataGrid fixed the issue.