Reputation: 61
I have a custom UserControl with a RadDataGrid and a ListView. The UserControl has an ItemsSource which, after some internal operations on the data, populates the ItemsSource properties of both the RadDataGrid and the ListView.
Once populated, I want to expose the ItemsSource property of the RadDataGrid to my view model.
To do this, I create a Dependency Property "GridItemsSource" in the code behind file with a TwoWay binding in the UserControl's XAML file as:
public static readonly DependencyProperty GridItemsSourceProperty = DependencyProperty.Register(nameof(GridItemsSource), typeof(object), typeof(ListViewGrid), new PropertyMetadata(null, OnItemsSourceChanged));
public object GridItemsSource
{
get { return GetValue(GridItemsSourceProperty); }
set { SetValue(GridItemsSourceProperty, value); }
}
And:
<grid:RadDataGrid x:Name="DataGrid"
Grid.Column="1"
UserGroupMode="Disabled"
AutoGenerateColumns="False"
ItemsSource="{x:Bind GridItemsSource, Mode=TwoWay}"
SelectedItem="{x:Bind SelectedGridItem, Mode=TwoWay}">
</grid:RadDataGrid>
In my page I also have a TwoWay binding to the GridItemsSource property as:
<userControls:ListViewGrid x:Name="ListViewGrid"
GridItemsSource="{x:Bind ViewModel.FormItems, Mode=TwoWay}"
SelectedGridItem="{x:Bind ViewModel.SelectedFormItem, Mode=TwoWay}"/>
And in my ViewModel:
private ObservableCollection<FormItem> formItems;
public ObservableCollection<FormItem> FormItems
{
get => formItems;
set => Set(ref formItems, value);
}
This works well for the "SelectedGridItem" alone, but when I bind the "GridItemsSource" the program stops at the setter of the Dependency Property with the following runtime error:
Unable to cast object of type 'System.Collections.Generic.List1[System.Object]' to type 'System.Collections.ObjectModel.ObservableCollection1[Models.FormItem]
.
Why do I get this error? All ItemsSource properties I have seen in other Controls are all of type object and binding to an ObservableCollection is not a problem with them.
Upvotes: 0
Views: 396
Reputation: 39092
I think the problem is that you use Mode=TwoWay
on the ItemsSource
properties. ItemsSource
property should be just "read-only" by the control. Try setting the GridItemsSource
and ItemsSource
properties to Mode=OneWay
only, so that the system doesn't try to reflect any changes to the view model which could cause the conversion problem.
Upvotes: 0