如何在DataGrid中合并两个不同的可观察集合
问题描述:
我想合并下面的集合并使用CompositeCollection将其绑定到DataGrid。如何在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为空。
答
谢谢你们。
我已经实现了我的要求如下图所示,
<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>
http://stackoverflow.com/questions/6446699/how-do-you-bind-a-collectioncontainer-to-a-collection-in- a-view-model – lerner1225
另一个示例:http://stackoverflow.com/q/19243109/109702尝试定义CompositeCollection,它是CollectionContainer项目的声明式而不是代码。 – slugster
如果我在猜测您的需求时没有错,您将无法通过'DataGrid'获得'CompositeCollection'所需的预期结果。 :) – Gopichandar