数据网格中的数据绑定与collectionviewsource

时间:2017-05-15 06:58:24

标签: c# wpf

我有一个ObservableCollection类

Public class Object
{
  public string Name;
  public Employee Employee;
}

public class Employee
{
  // few properties
}

这是我的CollectionViewSource的XMAL代码:

 <CollectionViewSource x:Key="cvsTasks"
                          Source="{Binding Reels}">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="Name" />
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>

这是我的DataGrid代码:

   <DataGrid  ItemsSource="{Binding Source={StaticResource cvsTasks}}"/>

现在CollectionViewSource在Name上有PropertyGroupDescription,我想将DataGrid与CollectionViewSource的Employee属性绑定。

1 个答案:

答案 0 :(得分:0)

我不知道,如果我正确理解你的问题。

查看:

<Window.Resources>
    <CollectionViewSource x:Key="cvsTasks" Source="{Binding List}">
        <CollectionViewSource.GroupDescriptions>
            <PropertyGroupDescription PropertyName="Name" />
        </CollectionViewSource.GroupDescriptions>
    </CollectionViewSource>
</Window.Resources>
<Grid >
    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Source={StaticResource cvsTasks}}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
            <DataGridTextColumn Header="EmpID" Binding="{Binding Employee.ID}"/>
            <DataGridTextColumn Header="EmpDeportment" Binding="{Binding Employee.Department}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

视图模型:

public class ViewModel {
    public System.Collections.ObjectModel.ObservableCollection<Model.Root> List { get; set; }

    public ViewModel() {
        List = new System.Collections.ObjectModel.ObservableCollection<Model.Root> {
            new Model.Root {
                Name = "Peter",
                Employee = new Model.Employee {
                    ID = 1,
                    Department = "IT"
                }
            },
            new Model.Root {
                Name = "Hans",
                Employee = new Model.Employee {
                    ID = 2,
                    Department = "accounting"
                }
            },
            new Model.Root {
                Name = "Bilbo",
                Employee = new Model.Employee {
                    ID = 3,
                    Department = "ceo"
                }
            }
        };
    }
}

型号:

public class Model {

        public class Employee {
            public int ID { get; set; }
            public string Department { get; set; }
        }
        public class Root {
            public string Name { get; set; }
            public Employee Employee { get; set; }
        }
    }

结果: enter image description here