ListView.GridViewColumn (*)宽度

47
我正在使用 WPF 应用程序中的 ListView 控件,而不是 DataGrid。 我想给我的 ListView.GridViewColumn 一个 * 的宽度,但每当我为 ListView.GridViewColumn 提供 * 宽度时,它会给我一个编译时错误。 请建议我如何提供 * 宽度以便在我最大化屏幕时,ListView.GridViewColumn可以自动填充额外的空间。

希望能得到任何有关此问题的帮助。谢谢。

2个回答

84

请尝试以下解决方案:

<ListView>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="column1" x:Name="col1"/>
            <!--Column that shall resize: Width is set to the Actual Width of the helper field defined below-->
            <GridViewColumn Header="column2" 
                            Width="{Binding ElementName=helperField, Path=ActualWidth}"/>
        </GridView>
    </ListView.View>
    Test Text
</ListView>

<!--This is the hidden helper Grid which does the resizing -->
<Grid Visibility="Hidden">
    <Grid.ColumnDefinitions>
        <!--Width is bound to width of the first GridViewColumn -->
        <ColumnDefinition Width="{Binding ElementName=col1, Path=ActualWidth}"/>
        <!--Width is set to "Fill"-->
        <ColumnDefinition Width="*"/>
        <!--Correction Width-->
        <ColumnDefinition Width="10"/>
    </Grid.ColumnDefinitions>
    <!--This is the hidden helper Field which is used to bind to, using the "Fill" column of the helper grid-->
    <Grid Grid.Column="1" x:Name="helperField"/>
</Grid>

你也可以在以下链接中找到其他解决方案:

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/3ee5696c-4f26-4e30-8891-0e2f95d69623/


感谢Bilal Hashmi。但是在上面的XAML方法中,我应该在我的XAML页面中放置<Grid visibility="Hidden">代码行,以便它会影响ListView列。使用IValueConverter时,它在屏幕加载时第一次运行得很好,但当我最大化屏幕或调整屏幕大小时,它不会相应地调整列宽。 - Yogesh
也许这可以帮助:https://dev59.com/7HRB5IYBdhLWcg3wpopm - Klaus78
你可以将它放在显示 ListView 的 XAML 页面的任何位置。比如说,放在页面主网格的 Row=0 和 Column=0 处。 - Bilal Hashmi
2
肯定是一个hack,但它足够简单且运行良好,我很喜欢它。 - JRadness
1
这是一个非常好的技巧。我遇到的主要问题是在自动模式下,ListView的滚动条出现和消失时,列宽需要自动更新。此外,我不喜欢“校正宽度”技巧。我的解决方案是将上述解决方案与Q#9907017结合起来,并绑定到ListView的ScrollViewer的“ViewportWidth”(不像答案中那样)。请注意,在ListView布局后通过挂接到LayoutUpdated(参见Q#4708039)在代码后台激活绑定。 - Guss
可能在列数较少的情况下还好,否则我担心这可能会存在扩展问题。 - user585968

4

我在这里发布了我的方法,与其他方法略有不同(但发现它非常可靠,并允许使用百分比宽度列https://dev59.com/6msy5IYBdhLWcg3wxQwj#10526024)。我尝试了上面的方法,但发现我的devenv.exe处理器最大化,因为它不断地尝试重新评估我的设计视图与上述动态绑定。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接