【问题标题】:Conversion from ReadOnlyObservableCollection to List<MyClass>从 ReadOnlyObservableCollection 转换为 List<MyClass>
【发布时间】:2013-07-17 03:48:42
【问题描述】:

我有一个带分组的数据网格,我正在尝试设置模板样式以添加一些关于组的摘要。

IN XAML DataGrid.RowGroupHeaderStyle

        <Grid Grid.Column="3" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Stretch" Margin="0,1,0,1" >
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="200"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <TextBlock Grid.Column="0" Text="{Binding Name}" Margin="4,0,0,0" />
            <TextBlock Grid.Column="1" Text="{Binding Items, Converter="{StaticResource summaryConverter}"}" />
        </Grid>

数据网格项来源的绑定

    PagedCollectionView collection = new PagedCollectionView(e.Result.ToList<MyClass>());
    collection.GroupDescriptions.Add(new PropertyGroupDescription("Name"));
    dataGrid.ItemsSource = collection;

我的班级

    class MyClass {
        public string Name;
        public double Value;
    }

我创建了一个转换器来获取同一组的项目,但我在将对象转换为 List&lt;MyClass&gt;() 时遇到了问题。我收到此错误

无法转换类型为“System.Collections.ObjectModel.ReadOnlyObservableCollection1[System.Object]' to type 'System.Collections.Generic.List1[MyClass]”的对象。 `

在 Converter.cs 中

    public object Convert(object values, Type targetType, object param, CultureInfo culture) {
        var source = (List<MyClass>)values;
    }

有人知道我应该如何进行转换吗??

【问题讨论】:

  • 为什么需要列表?
  • 因为item source是一个MyClass的列表,我想做列表内Value属性的求和

标签: c# silverlight datagrid


【解决方案1】:

使用 LINQ。

public object Convert(object values, Type targetType, object param, CultureInfo culture) {
    var source = (ReadOnlyObservableCollection<object>) values;
    List<MyClass> list = source.OfType<MyClass>().ToList();
    ...
}

【讨论】:

  • 这些转换不起作用。它返回无法转换类型为“System.Collections.ObjectModel.ReadOnlyObservableCollection1[System.Object]' to type 'System.Collections.ObjectModel.ReadOnlyObservableCollection1[MyClass]”的对象。
猜你喜欢
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 2021-11-11
相关资源
最近更新 更多