Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
405
Creating templatecolumns dinamically in code behind for different column numbers
posted

I have a view  with a XamGrid  bound to a viemodel.

The XamGrid  (AutogenerateColumns = false) binds its ItemsSource to an ObservableCollection in the ViewModel.

This grid needs to reusable and needs to be used with objects that have a different number of columns.

So, in xaml I defined the templateColumn for the first column (all object must have at least one column for the name). This columns is rendered fine

Then I pass in in code behind information on what extra columns to add. I do this after the datacontext has changed.

See my code below:

void XamGridDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)

{

                var viewModel = DataContext as MyViewModel;

                if (viewModel != null)

                {

                    foreach (var columnInfo in viewModel.ColumnsInfo)

                    {

 

                        var templateColumn = new TemplateColumn();

                        templateColumn.Key = columnInfo.Key;

                        templateColumn.Width = new ColumnWidth(columnInfo.Width, false);

                        templateColumn.HeaderText = columnInfo.ColumnHeaderName;

 

                        // Create the Itemtemplate for the new column

                        var Fef = new FrameworkElementFactory(typeof(TextBlock));

                        var PlaceBinding = new Binding();

                        Fef.SetBinding(TextBlock.TextProperty, PlaceBinding);

                        PlaceBinding.Path = new PropertyPath(columnInfo.ObjectProperty);

                        var DataTemplate = new DataTemplate { VisualTree = vFef };

                        DataTemplate.Seal();

 

                        templateColumn.ItemTemplate = DataTemplate;

 

                        // Add new column to grid

                        BrowserPaneXamGrid.Columns.Add(templateColumn);

                    }

                }

}

 

When I say ShowDialog on this view I get the following error:

{"The following key(s) do not correspond with the DataSource: \"Value\". If you'd like to add additional columns, please use the UnboundColumn type."}

 “Here, ‘Value’ is the value of column.Key from above.”

 

The dialog actually pops up and shows the grid with one extra column. And I do not seem to be able to add more. But that exception makes the dialog appear in the back and later on one cannot use the DialogResult because the dialog has not be properly shown/initialized.

In other words, I really need to get rid of that exception. What am I doing wrong?  

Parents Reply Children