我有一个基本程序,我正在尝试测试ListView
的可能布局,以便我可以在我的主项目中使用它。我在显示组的标题时遇到问题,我无法弄明白。这显然是一个具有约束力的问题,但经过大量搜索和阅读许多ListView
分组/标题相关的帖子后,我无法解决它。我更喜欢在XAML中完成所有操作,因为我的ViewModel不了解Views。我可以在处理组头时显示常规文本,但不能显示绑定。这是我的代码:
查看:
<Window.Resources>
<CollectionViewSource Source="{Binding Collection}" x:Key="GroupedItems">
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="RepNum" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Window.Resources>
<ListView HorizontalAlignment="Left" Height="300" Margin="10,10,0,0"
VerticalAlignment="Top" Width="497"
ItemsSource="{Binding Source={StaticResource GroupedItems}}">
<ListView.View>
<GridView>
<GridViewColumn Header="File Name"
DisplayMemberBinding="{Binding FileName}"/>
<GridViewColumn Header="Date Scanned"
DisplayMemberBinding="{Binding DateScanned}"/>
<GridViewColumn Header="Time Scanned"
DisplayMemberBinding="{Binding TimeScanned}"/>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding RepNum}" Margin="0,0,10,0"/>
<TextBlock Text="Text1" Margin="0,0,10,0"/>
<TextBlock Text="Text2"/>
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
ViewModel(非常脏,用于测试目的的快速风格):
public class MainWindowViewModel
{
public ObservableCollection<Record> Collection { get; set; }
public MainWindowViewModel()
{
Collection = new ObservableCollection<Record>();
Collection.Add(
new Record()
{
RepNum = "12345",
FileName = "12345.pdf",
DateScanned = "05/01/2014",
TimeScanned = "1802"
});
Collection.Add(
new Record()
{
RepNum = "12345",
FileName = "12345C1.pdf",
DateScanned = "05/03/2014",
TimeScanned = "1401"
});
Collection.Add(
new Record()
{
RepNum = "12345",
FileName = "12345S1.pdf",
DateScanned = "05/03/2014",
TimeScanned = "1408"
});
Collection.Add(
new Record()
{
RepNum = "643334",
FileName = "643334.pdf",
DateScanned = "02/01/2013",
TimeScanned = "1305"
});
Collection.Add(
new Record()
{
RepNum = "643334",
FileName = "643334S1.pdf",
DateScanned = "02/06/2013",
TimeScanned = "0805"
});
}
}
你可以通过查看我如何创建它的实例来猜测Record类的样子,因此没有什么特别之处。除了ListView
组标题之外,我在任何绑定上查看RepNum都没有问题。我显然要么缺少一个步骤,要么没有适当的绑定语法。但是,我无法理解。
这是它的样子:
如您所见,显示纯文本“Text1”和“Text2”,但不显示RepNum
属性。
我试过了:
Text="{Binding Source={StaticResource GroupedItems}, Path=RepNum}"
...但是每个标题显示第一组的RepNum
:
答案 0 :(得分:0)
嗯,我想我找到了一个正确的答案:
<StackPanel Orientation="Horizontal" DataContext="{Binding Items}">
<TextBlock Text="{Binding Path=RepNum}" Margin="0,0,10,0"/>
<TextBlock Text="Test1" Margin="0,0,10,0"/>
<TextBlock Text="Test2"/>
</StackPanel>
我想我必须将StackPanel的DataContext
设置为Items
然后我才能绑定到RepNum
。
如果有人有更好的方法,请告诉我。但是这个可行。
终于遇到了一个帮助我的答案:https://stackoverflow.com/a/19232635/2006048