Jack Malkovich
Jack Malkovich

Reputation: 806

WPF datagrid binding too slow

In my WPF application i generate datagrid with dynamic number of columns. Part of the code:

for (var i = datetime; i < datetime.AddDays(1); i+= TimeSpan.FromHours(1)){
    var column = new DataGridTemplateColumn();
    column.Header = (i+1).ToString();
    column.CellTemplate = (DataTemplate)XamlReader.Load(
            new MemoryStream(Encoding.Default.GetBytes(
                @"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'><TextBlock Text='{Binding Values[" + i + @"]." + propName + @"}'/></DataTemplate>"
            ))); 
    column.CellEditingTemplate = (DataTemplate)XamlReader.Load(
            new MemoryStream(Encoding.Default.GetBytes(
                @"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'><TextBox Text='{Binding Values[" + i + @"]." + propName + @", Mode=TwoWay}'/></DataTemplate>"
            ))); 
    dataGrid1.Columns.Add(column);
}
dataGrid1.ItemsSource = data;

<DataGrid EnableColumnVirtualization="true" EnableRowVirtualization="true" Name="dataGrid1" DockPanel.Dock="Top" AutoGenerateColumns="False" 
                   Height="120" Width="Auto" />

When my table contains 25 columns and 10 rows it's rendered too slowly(1 sec). How can i improve performance of data binding?

Upvotes: 0

Views: 624

Answers (1)

Isak Savo
Isak Savo

Reputation: 35944

You should use the same data template instance for all your columns.

Just move the XamlReader.Load() calls outside of the loop and use the same instances for all your columns:

var cellTemplate = (DataTemplate)XamlReader.Load(...);
var cellEditTemplate = (DataTemplate)XamlReader.Load(...);
for(...)
{
   //..
   column.CellTemplate = cellTemplate;
   column.CellEditingTemplate = cellEditTemplate;
   //...
}

Upvotes: 1

Related Questions