WPF DataGrid记录项焦点禁用及选中单元格虚线框去除问题
解决WPF DataGrid行选中时的焦点虚线框问题
我来帮你搞定这个困扰!你遇到的虚线框其实是WPF控件默认的焦点视觉样式,当单元格或行获得焦点时就会显示。下面给你几种简单有效的解决方法:
方法一:禁用单元格的焦点视觉样式
这是最直接的方案,只需要给DataGrid的单元格设置FocusVisualStyle="{x:Null}"就能去掉虚线框。把这段代码加到你的DataGrid里:
<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" HorizontalAlignment="Left" Background="#eceff5" RowHeaderWidth="0" AlternatingRowBackground="#fbfcfe" GridLinesVisibility="Horizontal" CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserSortColumns="True" SelectionMode="Single" SelectionUnit="FullRow"> <!-- 添加单元格样式,禁用焦点虚线框 --> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="FocusVisualStyle" Value="{x:Null}" /> </Style> </DataGrid.CellStyle> <!-- 这里放你的列定义 --> <!-- <DataGridColumns> ... </DataGridColumns> --> </DataGrid>
原理很简单:FocusVisualStyle属性专门控制控件获得焦点时的额外视觉反馈,设为{x:Null}就会完全禁用这个效果,同时不会影响行的选中样式。
方法二:同时禁用行和单元格的焦点样式
如果键盘导航时还是偶尔出现虚线框,可能是行本身也获得了焦点,这时可以同时给DataGridRow也设置相同的属性:
<DataGrid x:Name="dataGrid" ...> <!-- 禁用行的焦点视觉样式 --> <DataGrid.RowStyle> <Style TargetType="DataGridRow"> <Setter Property="FocusVisualStyle" Value="{x:Null}" /> </Style> </DataGrid.RowStyle> <!-- 禁用单元格的焦点视觉样式 --> <DataGrid.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="FocusVisualStyle" Value="{x:Null}" /> </Style> </DataGrid.CellStyle> <!-- 列定义 --> </DataGrid>
这样就能彻底消除任何焦点带来的虚线框,同时保留你原本设置的行选中效果。
验证效果
设置完之后,你可以用键盘的上下箭头切换行,或者点击行,应该就看不到之前的虚线框了,而行的选中背景色依然正常显示。
内容的提问来源于stack exchange,提问作者user9641573
相关产品推荐
相关产品推荐

