代码之家  ›  专栏  ›  技术社区  ›  JumpingJezza

拉伸UniformGrid并将其垂直对齐到顶部

  •  0
  • JumpingJezza  · 技术社区  · 8 年前

    我正在使用ItemsControl来显示1-10个项目的列表(通常是2-4个)。我正在努力满足所有这些要求:

    • 所有行的高度必须相同
    • 如果可能,所有行的显示高度应最大为300。
    • 如果没有足够的空间以300高显示所有行,则以尽可能大的高度显示。
    • 如果最大可能高度小于150,则以maxsize显示并使用滚动条

    这就是我到目前为止所做的:

    <Window x:Class="TestGridRows.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:vm="clr-namespace:TestGridRows"
            mc:Ignorable="d"
            d:DataContext="{d:DesignInstance vm:MainViewModel}"
            Height="570" Width="800">
    
        <ScrollViewer VerticalScrollBarVisibility="Auto">
            <ItemsControl ItemsSource="{Binding Path=DataItems}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Border MinHeight="150" MaxHeight="300" BorderBrush="DarkGray" BorderThickness="1" Margin="5">
                            <TextBlock Text="{Binding Path=TheNameToDisplay}" VerticalAlignment="Center" HorizontalAlignment="Center" />
                        </Border>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <UniformGrid Columns="1" IsItemsHost="True" />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </ScrollViewer>
    </Window>
    

    这是1项的当前外观: actual1

    看起来像: expected1


    actual3


    对于4个以上的项目,滚动条显示正确,但项目大小均为150,而不是300: actual4

    问题:

    当只有一个项目时,如何将内容与顶部对齐(在不破坏其他功能的情况下(显然)

    当有4个以上的项目时,如何将项目调整为maxheight而不是minheight?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Alex.Wei    7 年前

    在WPF布局过程中,将按顺序进行测量和安排。在大多数情况下,如果 UIElement Stretch , UIElement UniFormGrid 将始终返回160(即 Border.MinHeight + Border.Margin.Top + Border.Margin.Bottom )*测量结果中所需高度的项目计数(将存储在 DesiredSize.DesiredSize.Height ItemsControl.ActualHeight 因为它已经 伸展 VerticalAlignment UniFormGrid.DesiredSize.Height ItemsControl.ActualHeight , 任何孩子都有 伸展 垂直对齐 MaxHeight . 这就是为什么你的1项测试导致了该中心。如果你改变 UniFormGrid.VerticalAlignment 或 Border.VerticalAlignment 到 Top ,您将在顶部获得一个160高的项目 ItemsContorl .


    namespace WpfApp1
    {
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
        }
    
        public class MyScrollViewer : ScrollViewer
        {
            public double DesiredViewportHeight;
    
            public MyScrollViewer() : base() { }
    
            protected override Size MeasureOverride(Size constraint)
            {
                // record viewport's height for late calculation 
                DesiredViewportHeight = constraint.Height;
    
                var result = base.MeasureOverride(constraint);
    
                // make sure that `ComputedVerticalScrollBarVisibility` will get correct value 
                if (ComputedVerticalScrollBarVisibility == Visibility.Visible && ExtentHeight <= ViewportHeight)
                    result = base.MeasureOverride(constraint);
    
                return result;
            }
        }
    
        public class MyUniformGrid : UniformGrid
        {
            private MyScrollViewer hostSV;
            private ItemsControl hostIC;
    
            public MyUniFormGrid() : base() { }
    
            public double MaxRowHeight { get; set; }
            public double MinRowHeight { get; set; }
    
            protected override Size MeasureOverride(Size constraint)
            {
                if (hostSV == null)
                {
                    hostSV = VisualTreeHelperEx.GetAncestor<MyScrollViewer>(this);
                    hostSV.SizeChanged += (s, e) =>
                    {
                        if (e.HeightChanged)
                        {
                            // need to redo layout pass after the height of host had changed.  
                            this.InvalidateMeasure();
                        }
                    };
                }
    
                if (hostIC == null)
                    hostIC = VisualTreeHelperEx.GetAncestor<ItemsControl>(this);
    
                var viewportHeight = hostSV.DesiredViewportHeight;
                var rows = hostIC.Items.Count;
                var rowHeight = viewportHeight / rows;
                double desiredHeight = 0;
    
                // calculate the correct height
                if (rowHeight > MaxRowHeight || rowHeight < MinRowHeight)
                    desiredHeight = MaxRowHeight * rows;
                else
                    desiredHeight = viewportHeight;
    
                var result = base.MeasureOverride(constraint);
    
                return new Size(result.Width, desiredHeight);
            }
        }
    
        public class VisualTreeHelperEx
        {
            public static T GetAncestor<T>(DependencyObject reference, int level = 1) where T : DependencyObject
            {
                if (level < 1)
                    throw new ArgumentOutOfRangeException(nameof(level));
    
                return GetAncestorInternal<T>(reference, level);
            }
    
            private static T GetAncestorInternal<T>(DependencyObject reference, int level) where T : DependencyObject
            {
                var parent = VisualTreeHelper.GetParent(reference);
    
                if (parent == null)
                    return null;
    
                if (parent is T && --level == 0)
                    return (T)parent;
    
                return GetAncestorInternal<T>(parent, level);
            }
        }
    }
    

    <Window x:Class="WpfApp1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp1"
            xmlns:sys="clr-namespace:System;assembly=mscorlib"
            mc:Ignorable="d"
            Height="570" Width="800">
    
        <local:MyScrollViewer VerticalScrollBarVisibility="Auto">
            <ItemsControl>
                <sys:String>aaa</sys:String>
                <sys:String>aaa</sys:String>
                <sys:String>aaa</sys:String>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Border BorderBrush="DarkGray" BorderThickness="1" Margin="5">
                            <TextBlock Text="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType=ContentPresenter}}"
                                       VerticalAlignment="Center" HorizontalAlignment="Center" />
                        </Border>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <local:MyUniformGrid Columns="1"  MinRowHeight="150" MaxRowHeight="300" VerticalAlignment="Top"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </local:MyScrollViewer>
    </Window>