如何以这样的方式正确处理 ListView 的最后一列大小:
- listview 不显示丑陋且未使用的“额外”列(参见图片 1,或 here 例如)
- (实际)最后一列被拉伸(stretch)以填充剩余空间
- 不显示水平滚动条
- 在任何方向调整大小都不会留下人工痕迹(见下文)
我已经为此苦苦挣扎了很长一段时间,但没有成功,网络上的大量搜索也没有提供任何见解。这是我到目前为止所拥有的:
我首先尝试调整最后一列的宽度以完全填满整个 View ,但水平滚动条随后弹出。所以现在我将所有列的 ColumnHeaderContainerStyle 设置为不显示任何内容的透明样式,并用实际样式覆盖每个列上的 HeaderContainerStyle;对于最后一列,我将边距设置为负值,以便它填充源自额外列的额外空白空间。见图2
将最后一列宽度计算为 actualWidth 与考虑边距/填充的其他列宽度之和之间的差值
与 2 相同;宽度不能太小,否则显示水平滚动条
这是由 2 介绍的:如果最后一列的宽度设置为常量值,我可以毫无问题地增大和缩小。使用代码拉伸(stretch)列时, View 在增长时会适当拉伸(stretch),但在缩小 ListView 的一部分行时会消失。然而,列标题或多或少保持适当的大小,但仍然比正常情况小,参见图 3。这让我觉得收缩有一些特别之处:我所做的计算是相同的,但在视觉上却不同。但是,我无法在框架中找到发生这种情况的位置/方式。
图片:
Picture 1 http://deathwillendthiswar.dommel.be/default.jpg Picture 2 http://deathwillendthiswar.dommel.be/start.jpg Picture 3 http://deathwillendthiswar.dommel.be/afterdrag.jpg
用于拉伸(stretch)的代码,应用于 ListView 调整大小处理程序中的最后一列
int StretchLastColWidth( ListView lv, int minWidth )
{
double width = lv.ActualWidth;
if( width <= 0 )
return minWidth;
GridView grdView = lv.View as GridView;
for( int i = 0 ; i < grdView.Columns.Count - 1 ; ++i )
width -= ( grdView.Columns[ i ].ActualWidth + 6 ); //padding?
Decorator border = VisualTreeHelper.GetChild( lv, 0 ) as Decorator;
ScrollViewer scroll = border.Child as ScrollViewer;
if( scroll.ComputedVerticalScrollBarVisibility == System.Windows.Visibility.Visible )
width -= 14; //my scrollbar is smaller than the system default..
width -= 12 //comes from padding??
if( width > minWidth )
return Convert.ToInt32( width );
else
return minWidth;
}
Listview 的 xaml:
<ListView ItemContainerStyle="{StaticResource ListViewItemStyle}">
<ListView.View>
<GridView ColumnHeaderContainerStyle="{DynamicResource ListViewEmptyHeaderStyle}">
<GridViewColumn Width="80" Header="Hdr0" HeaderContainerStyle="{DynamicResource ListViewHeaderStyle}"/>
<GridViewColumn Header="Hdr1" HeaderContainerStyle="{DynamicResource ListViewLastHeaderStyle}"/>
</GridView>
</ListView.View>
</ListView>
如果真的需要,我可以发布整个模板;请注意,虽然我在显示图片时使用了相当多的修改样式,但使用未修改的标准 ListView 时结果完全相同。如果有人想尝试,请使用此样式查看项目行周围的边框:
<Style x:Key="ListViewItemStyle" TargetType ="{x:Type ListViewItem}">
<Setter Property="BorderBrush" Value="White"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Margin" Value="3,1"/> <!--if not used, border sticks to scrollbar etc-->
<Setter Property="SnapsToDevicePixels" Value="true"/>
</Style>
最佳答案
查看这篇 CodeProject 文章:
关于c# - 正确调整 wpf ListView 最后一列的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1872401/