问题
在 XAML 中使用了 MVVM 的模式实现布局切换,所以在 ListBox 中设置了每个 item 的模板,源码大概是这样子:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate DataType="app:ItemDemo">
<!--Your item layout here blabla-->
</DataTemplate>
<ListBox.ItemTemplate>
<!-- item list -->
</ListBox>
愉快地实现后,想在 Feedback 和 About 菜单之间加个分割条:
因为设置了 item 模板,所以直接加入到列表是没有效果的。
解决方案
这里使用 ItemContainerStyle 来实现。当窗口绘制时都会调用 ItemContainerStyle 来渲染每个 item,所以可以结合 Trigger 判断某个值以便替换不同的视图模板(如果不是很清楚建议先搜索 Style、Trigger、Setter):
<ListBox.ItemContainerStyle>
<!-- BaseOn 用于设置渲染样式继承 -->
<Style BasedOn="{ StaticResource MaterialDesignListBoxItem }">
<Style.Triggers>
<!-- 注意这里绑定的应该是你 item 数据对象的某个属性 -->
<!-- 通过这个值来判断是否替换默认视图模板 -->
<!-- {x:Null} 是系统命名空间中提供的 NULL 值 -->
<DataTrigger Binding="{Binding Content}" Value="{x:Null}">
<!-- 指定 ListBoxItem.Control.Template 的值,在 ControlTemplate 类型下包裹你的视图 -->
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<!-- I am here. -->
<Separator Margin="8" />
</ControlTemplate>
</Setter.Value>
</Setter>
<!-- 因为是分割线,所以禁用其点击响应 -->
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
之后在列表项目中将某个 item 的字段调为 NULL 即可:
...
<app:DemoItem Content="{x:Null}" />
...
最终画完一条万恶的分割线:
吐槽
笔者是 Google 几小时总结来的(怪我 Orz)