我有一个wpf列表视图,它有一个网格作为itemspanelTemplate。我根据项目的属性在正确的列和行中显示项目。但我想在网格的空单元格中放置一些控件。
这是我的代码和XAML的简化版本:
在参考资料中:
<ItemsPanelTemplate x:Key="TheTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
在XAML中:
<Controls:CustomListView ItemsSource="{Binding TheCollection}"
ItemsPanel="{DynamicResource TheTemplate}">
</Controls:CustomListView>
最后,在我的CustomListView中:
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
var viewModel = item as DomainObject;
if (viewModel != null)
{
element.SetValue(Grid.ColumnProperty, 1); //here I work with a converter, but this just simplifies it for StackOverflow
element.SetValue(Grid.RowProperty, 1);
}
}
注意:我知道我要投射到一个域对象,但请你放心。
这将给我一个网格,其中的项目在正确的行和列中。但是,如果我想在空单元格中显示一些内容,例如“空”之类的文本,该怎么办?
我不能只是将它添加到我的模板中,因为这样会使应用程序崩溃,并说itemscontrol将创建必要的控件。我已经尝试在代码隐藏中访问网格/模板,但无法找到如何访问。也许我不应该使用ListView?也许还有其他/更好的解决方案?