Column already belongs to a DataGrid instance and cannot be reassigned #4747
-
I'm working on a user control that has a DataGrid as part of it. I pass in columns to it similar to how the DataGrid accepts Columns: <CustomDataGrid>
<CustomDataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" />
</CustomDataGrid.Columns>
</CustomDataGrid> I add the columns to the DataGrid like this: foreach (var column in Columns)
{
_dataGrid.Columns.Add(column);
} The Columns property is defined like this: public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register(
"Columns",
typeof(ObservableCollection<DataGridColumn>),
typeof(CustomDataGrid),
new PropertyMetadata(new ObservableCollection<DataGridColumn>()));
public ObservableCollection<DataGridColumn> Columns
{
get => (ObservableCollection<DataGridColumn>)GetValue(ColumnsProperty);
set => SetValue(ColumnsProperty, value);
} It works perfectly fine but when navigating from a page that uses CustomDataGrid to another one that also uses it, I get the following exception:
If anyone could help me figure out a solution for fixing this I would appreciate it. I've tried clearing the columns list when the user control is unloaded but that doesn't work. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
@jhertel0 you don't want to create a new empty collection in your DependencyProperty definition. That'll create multiple different collections and all sorts of other bad things. See the docs here specify you need to initialize the collection in your constructor: https://docs.microsoft.com/windows/uwp/xaml-platform/custom-dependency-properties#initializing-the-collection It sounds like as you navigate you're trying to re-add columns to a different collection or something, so that's why it says that it already belongs elsewhere as the old ones exist. You'd have to remove them from the old collection when navigating away if they're getting criss-crossed or something - or if you're trying to re-use columns between the two grids from the binding. |
Beta Was this translation helpful? Give feedback.
@jhertel0 you don't want to create a new empty collection in your DependencyProperty definition. That'll create multiple different collections and all sorts of other bad things. See the docs here specify you need to initialize the collection in your constructor: https://docs.microsoft.com/windows/uwp/xaml-platform/custom-dependency-properties#initializing-the-collection
It sounds like as you navigate you're trying to re-add columns to a different collection or something, so that's why it says that it already belongs elsewhere as the old ones exist. You'd have to remove them from the old collection when navigating away if they're getting criss-crossed or something - or if you're trying to …