【发布时间】:2018-09-20 19:14:35
【问题描述】:
我有一个带有 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);
}
这仅适用于“SelectedGridItem”,但是当我绑定“GridItemsSource”时,程序会在依赖属性的设置器处停止,并出现以下运行时错误:
Unable to cast object of type 'System.Collections.Generic.List1[System.Object]' to type 'System.Collections.ObjectModel.ObservableCollection1[Models.FormItem].
为什么会出现此错误?我在其他控件中看到的所有 ItemsSource 属性都是对象类型,绑定到 ObservableCollection 对它们来说不是问题。
【问题讨论】:
标签: c# binding uwp dependency-properties