绑定包含数组的自定义对象的可观察集合

时间:2018-03-20 09:23:03

标签: c# wpf mvvm expandoobject dynamicobject

我正在学习wpf和绑定以及所有我有一个gridview和一个自定义对象

我正在尝试将自定义对象列表绑定到网格,我的自定义对象设计如下

 Public class myObject 
  {
    protected int myInt {get; set;}
    protected ObservableCollection<string> myStrings{get;set;}
    protected double myDouble{get;set}

    public myObject(int aInt, string aString, double aDouble)
   {
    myStrings = new ObservableCollection<string>(); 
    string[] substrings = aString.split('/');
    this.myInt = aInt;


     foreach (string s in substrings)
     {
         myStrings.Add(s);
     }

     this.myDouble = aDouble;
    }

}

所以我然后创建这些对象的observablecollection并将它们绑定到网格

double,int在网格中显示得很好但数组正在显示指针, 我有一个填充

的列
  "System.Collections.ObjectModel.ObservableCollection `1[System.String]" 

任何人都可以帮我在网格中显示observableCollection的内容,就像集合中的每个项目都会得到一个列。

先谢谢!

解决方案我找到了

我尝试使用模板,但它没有取悦我,所以我使用了ExpandoObjects 我首先创建了一个字典列表,其中包含我未来网格的每一行,然后使用https://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/将其转换为expando对象非常感谢他的自定义方法

然后我将ExpandoObjects的可观察集合绑定到我的radgridview和TADA我现在拥有动态对象的动态网格

再次感谢您的回答我在模板上学到了一些有用的信息!

1 个答案:

答案 0 :(得分:1)

在您的情况下看起来更合适的是使用RowDetailsTemplate来定义子DataGrid / GridView以显示字符串集合,将字符串集合显示在与另一个相同的级别上属性可能是一项艰巨的任务(并没有多大意义)。 这里有一个如何在另一个DataGrid中定义GridView的示例(使用ListView / DataGrid同样的事情, <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="MyInt" Binding="{Binding MyInt}"/> <DataGridTextColumn Header="MyDouble" Binding="{Binding MyDouble}"/> </DataGrid.Columns> <DataGrid.RowDetailsTemplate> <DataTemplate> <ListView ItemsSource="{Binding MyStrings}"/> </DataTemplate> </DataGrid.RowDetailsTemplate> </DataGrid> 看起来更合适。)

public class MyObject
{
    public int MyInt { get; set; }
    public ObservableCollection<string> MyStrings { get; set; }
    public double MyDouble { get; set; }

    public MyObject(int aInt, string aString, double aDouble)
    {
        MyStrings = new ObservableCollection<string>();
        string[] substrings = aString.Split('/');
        this.MyInt = aInt;


        foreach (string s in substrings)
        {
            MyStrings.Add(s);
        }

        this.MyDouble = aDouble;
    }

}

为MyObject

{{1}}