类型对象的UWP依赖项属性未绑定到ObservableCollection

时间:2018-04-11 03:21:32

标签: c# binding uwp dependency-properties

我有一个带有RadDataGrid和ListView的自定义UserControl。 UserControl有一个ItemsSource,在对数据进行一些内部操作之后,填充RadDataGrid和ListView的ItemsSource属性。

填充后,我想将RadDataGrid的ItemsSource属性公开给我的视图模型。

为此,我创建了一个依赖属性" GridItemsSource"在UserControl的XAML文件中带有TwoWay绑定的代码隐藏文件中:

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); }
}

<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>

在我的页面中,我还有一个与GridItemsSource属性的TwoWay绑定:

<userControls:ListViewGrid x:Name="ListViewGrid"
                           GridItemsSource="{x:Bind ViewModel.FormItems, Mode=TwoWay}"
                           SelectedGridItem="{x:Bind ViewModel.SelectedFormItem, Mode=TwoWay}"/>

在我的ViewModel中:

private ObservableCollection<FormItem> formItems;
public ObservableCollection<FormItem> FormItems
{
    get => formItems;
    set => Set(ref formItems, value);
}

这适用于&#34; SelectedGridItem&#34;单独,但当我绑定&#34; GridItemsSource&#34;程序在Dependency属性的setter处停止,并出现以下运行时错误:

Unable to cast object of type 'System.Collections.Generic.List1[System.Object]' to type 'System.Collections.ObjectModel.ObservableCollection1[Models.FormItem]

为什么会出现此错误?我在其他控件中看到的所有ItemsSource属性都是类型对象,并且与ObservableCollection的绑定对它们来说不是问题。

1 个答案:

答案 0 :(得分:0)

我认为问题是您在Mode=TwoWay属性上使用ItemsSourceItemsSource属性应该只是控件的“只读”。尝试仅将GridItemsSourceItemsSource属性设置为Mode=OneWay,以便系统不会尝试反映可能导致转换问题的视图模型的任何更改。

相关问题