如何在DataGrid中合并两个不同的可观察集合

时间:2016-09-06 12:28:33

标签: wpf datagrid

我想组合下面的集合,并使用CompositeCollection将其绑定到DataGrid。

   private ObservableCollection<LabelDataInfo> labelSource;

    public ObservableCollection<LabelDataInfo> LabelSource
    {
        get { return labelSource; }
        set { labelSource = value; }
    }
    private ObservableCollection<NumericalDataInfo> numericLabelSource;

    public ObservableCollection<NumericalDataInfo> NumericLabelSource
    {
        get { return numericLabelSource; }
        set { numericLabelSource = value; }
    }
    private CompositeCollection mergedSource;

    public CompositeCollection MergedSource
    {
        get { return mergedSource; }
        set { mergedSource = value; OnPropertyChanged("MergedSource"); }
    }

 public MergedTargetDataInfo()
    {
        var labelInfo = new ObservableCollection<LabelDataInfo>();
        labelInfo.Add(new LabelDataInfo() { Title = "Title1", Label = "Label1" });
        labelInfo.Add(new LabelDataInfo() { Title = "Title2", Label = "Label2" });
        labelInfo.Add(new LabelDataInfo() { Title = "Title3", Label = "Label3" });

        LabelSource = labelInfo;

        var numericInfo = new ObservableCollection<NumericalDataInfo>();
        numericInfo.Add(new NumericalDataInfo() { NumericTitle = "NumericTitle1", NumericLabel = "NLabel1" });
        numericInfo.Add(new NumericalDataInfo() { NumericTitle = "NumericTitle2", NumericLabel = "NLabel2" });
        numericInfo.Add(new NumericalDataInfo() { NumericTitle = "NumericTitle3", NumericLabel = "NLabel3" });
        NumericLabelSource = numericInfo;


       mergedSource = new CompositeCollection();
        CollectionContainer collection1 = new CollectionContainer() { Collection = LabelSource };
        CollectionContainer collection2 = new CollectionContainer() { Collection = NumericLabelSource };          
        mergedSource.Add(collection1);
        mergedSource.Add(collection2);        
    }



<DataGrid ItemsSource="{Binding MergedSource}" AutoGenerateColumns="True"/>

但它显示为空格。如何在wpf中合并Label和NumericLabelDataSource? 如何在DataGrid控件中显示combosite集合。尝试绑定CompositeCollection时,DataGrid为空。

1 个答案:

答案 0 :(得分:0)

谢谢你们。

我已达到我的要求,如下所示,

<DataGrid AutoGenerateColumns="False">
        <DataGrid.ItemsSource>
            <CompositeCollection>
                <CollectionContainer Collection="{Binding  Source={StaticResource viewModel}, Path=LabelSource}"/>
                <CollectionContainer Collection="{Binding Source={StaticResource viewModel},Path=NumericLabelSource}"/>
            </CompositeCollection>
        </DataGrid.ItemsSource>
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Title}"/>
            <DataGridTextColumn Binding="{Binding Label}"/>
        </DataGrid.Columns>
    </DataGrid>