GridView列宽调整

本文关键字:调整 GridView | 更新日期: 2023-09-27 18:22:05

我的UI:

<ListView Name="persons" SelectionChanged="persons_SelectionChanged">
        <ListView.View>
            <GridView AllowsColumnReorder="False">
                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="auto"/>
                <GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}" Width="auto"/>
            </GridView>
        </ListView.View>
    </ListView>

我的UI的代码背后:

internal void Update(IEnumerable<Person> pers)
    {
        this.persons.ItemsSource = null;
        this.persons.ItemsSource = pers;
        UpdateLayout();
    }

我的实体:

class Person
{
   public string Name { get; set; }
   public int Age { get; set; }
}

GridViewColumns的宽度与GridViewColumn标头的宽度相同。即使我用长名称的Persons调用Update()。列的大小不会调整。

a) 如何自动将"名称"列(当我调用Update时)调整为最长名称的长度,但不超过值x(我想指定列的最大宽度)?

b) 如何指定"年龄"列填充控件末尾的空间(以便网格视图的列使用控件的整个宽度)?

GridView列宽调整

GridView不会自动调整大小。

要调整列的大小,您可以

    foreach (GridViewColumn c in gv.Columns)
    {
        // Code below was found in GridViewColumnHeader.OnGripperDoubleClicked() event handler (using Reflector)
        // i.e. it is the same code that is executed when the gripper is double clicked
        // if (adjustAllColumns || App.StaticGabeLib.FieldDefsGrid[colNum].DispGrid)
        if (double.IsNaN(c.Width))
        {
            c.Width = c.ActualWidth;
        }
        c.Width = double.NaN;
     }  

至于最后填充区域的大小,我用转换器来完成。我不认为这个转换器正是你需要的,但它应该让你开始。

    <GridViewColumn Width="{Binding ElementName=lvCurDocFields, Path=ActualWidth, Converter={StaticResource widthConverter}, ConverterParameter=100}">

    [ValueConversion(typeof(double), typeof(double))]
    public class WidthConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // value is the total width available
            double otherWidth;
            try
            {
                otherWidth = System.Convert.ToDouble(parameter);
            }
            catch
            {
                otherWidth = 100;
            }
            if (otherWidth < 0) otherWidth = 0;
            double width = (double)value - otherWidth;
            if (width < 0) width = 0;
            return width; // columnsCount;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

GridView速度很快,但需要一些婴儿看护。

我从"如何在WPF中自动调整GridViewColumn数据的大小并右对齐?"?

<Window.Resources>
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
</Window.Resources>

这对你有帮助吗?