应用MaterialDesignInXamlToolkit主题后ListView出现意外矩形区域的技术问询
解决MaterialDesignInXamlToolkit中ListView多余ListBoxChrome(Bd)区域的问题
我之前也碰到过一模一样的情况——MaterialDesign主题给ListView默认加了个叫Bd的ListBoxChrome元素,它原本是用来实现传统WPF ListView的边框和背景效果,但在MaterialDesign的设计体系里反而会多出一块不必要的区域,用Snoop确实一查一个准。
下面给你几个针对性的解决办法,既能保留MaterialDesign的其他样式特性,又能去掉这个多余区域:
1. 重写ListView模板,精准移除Bd元素
你可以基于MaterialDesign的ListView样式,只修改模板部分去掉ListBoxChrome,这样不会破坏其他MaterialDesign的样式逻辑:
<UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <!-- 先引入MaterialDesign的ListView主题资源 --> <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.ListView.xaml" /> <!-- 这里替换成你项目里实际的MaterialDesign资源路径 --> </ResourceDictionary.MergedDictionaries> <!-- 自定义ListView样式,继承MaterialDesign样式并修改模板 --> <Style TargetType="{x:Type ListView}" BasedOn="{StaticResource MaterialDesignListView}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListView}"> <Border x:Name="RootBorder" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}"> <!-- 直接移除原来的ListBoxChrome(Bd),用ScrollViewer包裹ItemsPresenter --> <ScrollViewer Focusable="false" Padding="{TemplateBinding Padding}"> <ItemsPresenter /> </ScrollViewer> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="false"> <Setter TargetName="RootBorder" Property="Opacity" Value="0.5" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> </UserControl.Resources>
2. 直接隐藏Bd元素(更轻量化)
如果不想重写整个模板,你可以通过指定样式键的方式,精准隐藏ListView内部的Bd元素:
<UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="../你的MaterialDesign资源路径.xaml" /> </ResourceDictionary.MergedDictionaries> <!-- 针对ListView内部的Bd元素设置隐藏 --> <Style TargetType="{x:Type ListBoxChrome}" x:Key="{x:Static ListView.BdStyleKey}"> <Setter Property="Visibility" Value="Collapsed" /> </Style> </ResourceDictionary> </UserControl.Resources>
这个方法的好处是不用动整个模板,只针对那个多余的元素下手,不会影响ListView的其他样式表现。
3. 排查是否误用了ListBox样式
有时候可能是因为ListView意外继承了ListBox的样式导致的,你可以明确给ListView指定MaterialDesign的样式,避免样式混淆:
<ListView Style="{StaticResource MaterialDesignListView}" ...> <!-- 你的列表内容 --> </ListView>
另外你提到尝试用默认的ListView样式,这种做法会完全丢失MaterialDesign的所有样式效果,不太推荐,还是上面两种针对性修改的方案更靠谱。
内容的提问来源于stack exchange,提问作者jchristof
相关产品推荐
相关产品推荐

