【问题标题】:How to make CollectionViewSource display List on a DataGrid如何使 CollectionViewSource 在 DataGrid 上显示列表
【发布时间】:2014-04-17 12:43:08
【问题描述】:

我有 3 个数据网格。第二个和第三个数据网格应仅显示第一个数据网格中基于第一个数据网格上所选行的值的子集。

C#:

_context.MyFor.Load();
F = new ObservableCollection<DB.Forum>(_context.MyFor.Local);

在 XAML 中我定义了资源:

<Window.Resources>
    <CollectionViewSource Source="{Binding F}" x:Key="CVSF" x:Name="CVSF" />
    <CollectionViewSource Source="{Binding FUsers, Source={StaticResource CVSF}}" x:Key="CVSUsers" x:Name="CVSUsers" />
    <CollectionViewSource Source="{Binding FOptions, Source={StaticResource CVSF}}" x:Key="CVSOptions" x:Name="CVSOptions" />
</Window.Resources>

绑定是这样完成的:

// Datagrid 1:
<DataGrid ItemsSource="{Binding Source={StaticResource CVSF}}" />

// Datagrid 2:
<DataGrid ItemsSource="{Binding Source={StaticResource CVSUsers}}">
   <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding User.UserUsername}" Header="UserName" x:Name="UserCol2" />
   </DataGrid.Columns>
</DataGrid>

// Datagrid 3:
<DataGrid ItemsSource="{Binding Source={StaticResource CVSOptions}}" PresentationTraceSources.TraceLevel="High" >
   <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding CountryName}" Header="Country1" />
      <DataGridTextColumn Binding="{Binding Country.CountryName}" Header="Country2" />
      <DataGridTextColumn Binding="{Binding ForumOptions.Country.CountryName}" Header="Country3" />
   </DataGrid.Columns>
</DataGrid>

问题:第一个数据网格显示所有内容。第二个仅显示那些属于第一个数据网格选择的用户(如预期的那样)。 但是第三个数据网格什么也没显示(见下面的错误)。我猜是因为返回的是一个对象(不是 CollectionView)。

System.Windows.Data Error: 5 : Value produced by BindingExpression 
is not valid for target property.;
Value='System.Data.Entity.DynamicProxies.ForumOptions_0DF21D7'
BindingExpression:Path=ForumOptions; 
DataItem='ListCollectionView' (HashCode=34116599); 
target element is 'CollectionViewSource' (HashCode=62307935); 
target property is 'Source' (type 'Object')

如何让相关结果显示在第三个datagrid上?

【问题讨论】:

  • FOptions 项是否具有属性CountryNameCountryForumOptions
  • 是的,它有。我认为问题出在类型不匹配的某个地方。例如,第二个数据网格工作正常,因为 FUsers 返回的是一个集合,但是 FOptions 只返回一个对象,它与 CollectionViewSource 资源冲突。我就是不知道怎么解决。

标签: c# wpf data-binding datagrid collectionviewsource


【解决方案1】:

终于找到了解决办法。我没有绑定到单独的 CollectionViewSource,而是将第一个数据网格命名为 x:Name="FList",然后使用绑定到 ElementName=FList, Path=SelectedItem,然后定义了所需属性的路径

<StackPanel DataContext="{Binding ElementName=FList, Path=SelectedItem, Mode=TwoWay}" Name="StackPanel2" >
    <TextBox Text="{Binding Path=ForumOptions.Country.CountryName}"/>
</StackPanel>

【讨论】:

    猜你喜欢
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多