【问题标题】:UWP Dependency Property of type object not binding to ObservableCollection类型对象的 UWP 依赖属性未绑定到 ObservableCollection
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 2017-03-23
      • 2019-10-31
      • 2020-08-06
      • 2018-01-23
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 2016-03-10
      相关资源
      最近更新 更多