I am writing an application that uses a GridView. I am dynamically creating GridViewColumns and setting their CellTemplate.VisualTree property to a FrameworkElementFactory that creates a StackPanel containing some other elements. The DataContext of the StackPanel is being bound to an item contained in a collection in the dataitem. Basically, each dataitem contains a collection of items corresponding to each column.
FrameworkElementFactory grFactory = new FrameworkElementFactory(typeof(StackPanel));
grFactory.SetBinding(StackPanel.DataContextProperty, new Binding(string.Format("DatedContainers[{0}]", colIndex)));
DataTemplate template = new DataTemplate();
template.VisualTree = grFactory;
gvc = new GridViewColumn();
gvc.CellTemplate = template;
gv.Columns.Add(gvc);
The column creation code works great, but if I later remove columns from the DataGrid (I also change the length of the collections in the dataitems), they appear to still be be bound to the dataitems. I get errors like the following:
System.Windows.Data Error: 16 : Cannot get 'Item[]' value (type 'DatedContainer') from 'DatedContainers' (type 'ObservableCollection`1'). BindingExpression:Path=DatedContainers[25]; DataItem='Student' (HashCode=32033579); target element is 'StackPanel' (Name=''); target property is 'DataContext' (type 'Object') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
The exceptions don't crash the application but appear to seriously affect performance. Is there something that I should be doing to remove these bindings when removing columns from the GridView?