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?
Hello Roberta,
Thank you for your feedback. I am glad that you resolved your issue and I believe that other community members may benefit from this as well.
Thanks again.
OK I figured it out. Basically when one creates columns dynamically, he she needs to use indexed binding for the key.
Thank you for your quick reply but that is not the problem. I did however remove any template definition from my xaml (just to be absolutely sure) and I still get the issue. Is there any sample code I can look at to resolve this?
Thank you for your post. I have been looking into it and I believe that you try to add the column that you already defined in XAML again in code behind. You can try to remove it from XAML. This message pops up when you try to add a Column with Key which has already been added to the XamGrid’s Columns collection. Please let me know if this helps you or you have further questions on this matter.
Looking forward for your reply.