假设我有以下两个类:
public class TestResults
{
public string TestGroup {get; set; }
public string TestName {get; set; }
public bool TestPassed {get; set; }
}
public class TestSummary
{
public string TestGroup {get; set; }
public string SummaryText {get; set; }
}
我的一些测试数据可能如下所示:
TestResults
TestGroup TestName TestPassed
==========================================
Item1 HasPrice True
Item1 HasDiscount True
Item2 HasPrice True
Item2 HasDiscount False
TestSummary
TestGroup SummaryText
=================================================
Item1 SKU: 234 Price: 13.40 Discount: 1.34
Item2 SKU: 345 Pirce: 15.70
如果我有IEnumerable<TestResults>
以及IEnumerable<TestSummary>
,我希望能够在TestGroup
上将它们组合在一起并显示其信息,如下所示:
______________________________________________________________________
| Item1 _________________________ _______________________________ |
| | Grid of TestResults | | SummaryText for Item1 | |
| |_______________________| |______________________________| |
|_____________________________________________________________________|
______________________________________________________________________
| Item2 _________________________ _______________________________ |
| | Grid of TestResults | | SummaryText for Item2 | |
| |_______________________| |______________________________| |
|_____________________________________________________________________|
我有2个问题可以解决这个问题:
IEnumerable
并将它们组合在一起,以便它们可以被datatemplate使用?答案 0 :(得分:4)
我认为您需要创建一个新类ItemViewModel,它将包含相应的TestResults和SummaryText作为您可以绑定的属性。比你能够创建一个IEnumerable的ItemViewModels并绑定你的ListView(或任何你想要的)。我还建议Grid of TestResults
最好用绑定到视图模型的TestResults属性的ListView替换。
希望这有帮助!简要描述 - 如果我的解释不够明确,请发表评论。
<强> UPD:强>
此代码应填充IEnumerable视图模型:
public class ItemViewModel
{
public IEnumerable<string> TestResults { get; set; }
public string SummaryText { get; set; }
}
...
var viewModels = testResults.Select(tr =>
new ItemViewModel() {
TestResults = testResults.Where(t => t.TestGroup == tr.TestGroup)
.Select(t => t.TestName + " " + t.TestPassed),
SummaryText = testSummaries.First(ts => ts.TestGroup == tr.TestGroup)
});
<强> UPD2:强>
这个XAML应该可以解决这个问题:
<!-- In your resources -->
<DataTemplate x:Key="ItemViewModelTemplate">
<StackPanel Orientation="Horizontal">
<ListView ItemsSource={Binding TestResults} />
<TextBlock Text={Binding SummaryText} />
</StackPanel>
</DataTemplate>
...
<!-- In your main xaml file -->
<!-- Let's assume that your main VM contains property ViewModels
that is filled like described above -->
<ListView ItemsSource={Binding ViewModels}
ItemTemplate="{StaticResource ItemViewModelTemplate}" />