c# - 自定义自动调整大小的WPF面板类

标签 c# wpf custom-controls panel

我试图通过重写PanelMeasureOverride为WPF编写一个自定义ArrangeOverride类,但是尽管它在大多数情况下都在工作,但我遇到了一个我无法解释的奇怪问题。

特别是,在弄清楚子项的大小后,我在Arrange的子项上调用ArrangeOverride后,它们的大小没有达到我给它们的大小,并且似乎已调整为Measure中传递给其MeasureOverride方法的大小。

我在该系统应该如何工作方面缺少什么吗?我的理解是,调用Measure只会使 child 根据所提供的availableSize评估其DesiredSize,而不会影响其实际最终尺寸。

这是我的完整代码(Panel,btw,旨在以最节省空间的方式排列子级,为不需要它的行提供较少的空间,并将剩余空间平均分配给其余的空间,目前仅支持垂直方向,但我打算在水平方向正常工作后再添加水平方向):

编辑:感谢您的答复。一会儿我将更仔细地研究它们。但是,让我澄清一下我预期的算法是如何工作的,因为我没有对此进行解释。

首先,思考我在做什么的最好方法是想象一个将每行设置为*的网格。这样可以将空间平均分配。但是,在某些情况下,行中的元素可能并不需要所有的空间。如果是这种情况,我想获取任何剩余的空间,并将其分配给可以使用该空间的那些行。如果没有行需要任何额外的空间,我只是尝试均匀地隔开空间(这就是extraSpace所做的,仅适用于这种情况)。

我分两次通过。第一遍的最终目的是确定一行的最终“正常大小”,即将缩小的行的大小(给定的大小小于其期望的大小)。我这样做是通过将最小的项目逐步放大到最大,然后在每个步骤中调整计算得出的正常大小,方法是将每个小项目的剩余空间添加到随后的每个大项目中,直到没有其他项目“适合”然后折断​​。

在下一个过程中,我将使用此正常值来确定某个项目是否适合,只需简单地将正常大小的Min与该项目的所需大小一起使用即可。

(为简单起见,我还将匿名方法更改为lambda函数。)

编辑2:我的算法似乎可以很好地确定 child 的适当大小。但是, children 只是不接受他们给定的尺寸。我通过传递PositiveInfinity并返回Size(0,0)来尝试了哥布林建议的MeasureOverride,但这使子级绘制自己,好像根本没有空间限制。对此不明显的部分是由于对Measure的调用而发生的。微软在这个主题上的文档还不清楚,因为我已经多次阅读了每个类和属性的描述。但是,现在很清楚,调用Measure实际上确实会影响子代的呈现,因此我将尝试按照BladeWise的建议在这两个函数之间进行逻辑划分。

解决了! 我知道了。正如我所怀疑的,我需要对每个 child 两次调用Measure()(一次评估DesiredSize,第二次给每个 child 适当的高度)。对我来说,WPF中的布局将以这种奇怪的方式设计似乎很奇怪,在该布局中它分为两遍,但Measure遍实际上做了两件事:度量和确定子级的大小,而Arrange遍除了实际物理上几乎什么也没做安置 children 。很奇怪

我将工作代码发布在底部。

首先,原始(残破)代码:

protected override Size MeasureOverride( Size availableSize ) {
    foreach ( UIElement child in Children )
        child.Measure( availableSize );

    return availableSize;
}

protected override System.Windows.Size ArrangeOverride( System.Windows.Size finalSize ) {
    double extraSpace = 0.0;
    var sortedChildren = Children.Cast<UIElement>().OrderBy<UIElement, double>( child=>child.DesiredSize.Height; );
    double remainingSpace = finalSize.Height;
    double normalSpace = 0.0;
    int remainingChildren = Children.Count;
    foreach ( UIElement child in sortedChildren ) {
        normalSpace = remainingSpace / remainingChildren;
        if ( child.DesiredSize.Height < normalSpace ) // if == there would be no point continuing as there would be no remaining space
            remainingSpace -= child.DesiredSize.Height;
        else {
            remainingSpace = 0;
            break;
        }
        remainingChildren--;
    }

    // this is only for cases where every child item fits (i.e. the above loop terminates normally):
    extraSpace = remainingSpace / Children.Count;
    double offset = 0.0;

    foreach ( UIElement child in Children ) {
        //child.Measure( new Size( finalSize.Width, normalSpace ) );
        double value = Math.Min( child.DesiredSize.Height, normalSpace ) + extraSpace;
            child.Arrange( new Rect( 0, offset, finalSize.Width, value ) );
        offset += value;
    }

    return finalSize;
}

这是工作代码:
double _normalSpace = 0.0;
double _extraSpace = 0.0;

protected override Size MeasureOverride( Size availableSize ) {
    // first pass to evaluate DesiredSize given available size:
    foreach ( UIElement child in Children )
        child.Measure( availableSize );

    // now determine the "normal" size:
    var sortedChildren = Children.Cast<UIElement>().OrderBy<UIElement, double>( child => child.DesiredSize.Height );
    double remainingSpace = availableSize.Height;
    int remainingChildren = Children.Count;
    foreach ( UIElement child in sortedChildren ) {
        _normalSpace = remainingSpace / remainingChildren;
        if ( child.DesiredSize.Height < _normalSpace ) // if == there would be no point continuing as there would be no remaining space
            remainingSpace -= child.DesiredSize.Height;
        else {
            remainingSpace = 0;
            break;
        }
        remainingChildren--;
    }
    // there will be extra space if every child fits and the above loop terminates normally:
    _extraSpace = remainingSpace / Children.Count; // divide the remaining space up evenly among all children

    // second pass to give each child its proper available size:
    foreach ( UIElement child in Children )
        child.Measure( new Size( availableSize.Width, _normalSpace ) );

    return availableSize;
}

protected override System.Windows.Size ArrangeOverride( System.Windows.Size finalSize ) {
    double offset = 0.0;

    foreach ( UIElement child in Children ) {
        double value = Math.Min( child.DesiredSize.Height, _normalSpace ) + _extraSpace;
        child.Arrange( new Rect( 0, offset, finalSize.Width, value ) );
        offset += value;
    }

    return finalSize;
}

必须两次调用Measure(并重复三次Children)可能不是很高效,但是它可以工作。对算法的任何优化将不胜感激。

最佳答案

让我们看看我是否正确,Panel应该如何工作:

  • 应该确定每个UIElement
  • 的所需大小
  • 取决于此类大小,它应该确定是否有一些可用空间
  • 如果存在这样的空间,则应调整每个UIElement的大小,以便填充整个空间(即,每个元素的大小将增加剩余空间的一部分)

  • 如果我做对了,您当前的实现无法完成此任务,因为您需要更改子项本身的所需大小,而不仅是更改其渲染大小(这是通过Measure和Arrange传递完成的)。

    请记住,在给定大小限制(传递给方法的UIElement)的情况下,Measure传递用于确定availableSize需要多少空间。在Panel的情况下,它也会对其子级调用Measure传递,但是并未设置其子级的所需大小(换句话说,子级的大小是面板的测量传递的输入)。
    至于Arrange传递,它用于确定最终将呈现UI元素的矩形,而不管所测量的大小如何。在Panel的情况下,它也会在其子级上调用Arrange传递,但是就像小节传递一样,不会更改子级的所需大小(它只会定义其渲染空间)。

    要实现所需的行为,请执行以下操作:
  • 在Measure和Arrange传递之间正确分割逻辑(在您的代码中,所有逻辑都在Arrange传递中,而用于确定每个 child 需要多少空间的代码应放在Measure传递中)
  • 使用适当的AttachedProperty(即RequiredHeight)代替所需的子项大小(除非将子项大小设置为Auto,否则您无法控制子项大小,因此无需采取DesiredSize)

  • 由于不确定我是否了解该小组的目的,因此我写了一个例子:

    创建一个新的Wpf解决方案(WpfApplication1)并添加一个新的类文件(CustomPanel.cs *)

    b。 打开CustomPanel.cs文件并粘贴此代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Controls;
    using System.Windows;
    
    namespace WpfApplication1
    {
     public class CustomPanel : Panel
     {
    
      /// <summary>
      /// RequiredHeight Attached Dependency Property
      /// </summary>
      public static readonly DependencyProperty RequiredHeightProperty = DependencyProperty.RegisterAttached("RequiredHeight", typeof(double), typeof(CustomPanel), new FrameworkPropertyMetadata((double)double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnRequiredHeightPropertyChanged)));
    
      private static void OnRequiredHeightPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
      { 
    
      }
    
      public static double GetRequiredHeight(DependencyObject d)
      {
       return (double)d.GetValue(RequiredHeightProperty);
      }
    
      public static void SetRequiredHeight(DependencyObject d, double value)
      {
       d.SetValue(RequiredHeightProperty, value);
      }
    
      private double m_ExtraSpace = 0;
    
      private double m_NormalSpace = 0;
    
      protected override Size MeasureOverride(Size availableSize)
      {
       //Measure the children...
       foreach (UIElement child in Children)
        child.Measure(availableSize);
    
       //Sort them depending on their desired size...
       var sortedChildren = Children.Cast<UIElement>().OrderBy<UIElement, double>(new Func<UIElement, double>(delegate(UIElement child)
       {
        return GetRequiredHeight(child);
       }));
    
       //Compute remaining space...
       double remainingSpace = availableSize.Height;
       m_NormalSpace = 0.0;
       int remainingChildren = Children.Count;
       foreach (UIElement child in sortedChildren)
       {
        m_NormalSpace = remainingSpace / remainingChildren;
        double height = GetRequiredHeight(child);
        if (height < m_NormalSpace) // if == there would be no point continuing as there would be no remaining space
         remainingSpace -= height;
        else
        {
         remainingSpace = 0;
         break;
        }
        remainingChildren--;
       }
    
       //Dtermine the extra space to add to every child...
       m_ExtraSpace = remainingSpace / Children.Count;
       return Size.Empty;  //The panel should take all the available space...
      }
    
      protected override System.Windows.Size ArrangeOverride(System.Windows.Size finalSize)
      {
       double offset = 0.0;
    
       foreach (UIElement child in Children)
       {
        double height = GetRequiredHeight(child);
        double value = (double.IsNaN(height) ? m_NormalSpace : Math.Min(height, m_NormalSpace)) + m_ExtraSpace;
        child.Arrange(new Rect(0, offset, finalSize.Width, value));
        offset += value;
       }
    
       return finalSize;   //The final size is the available size...
      }
     }
    }
    

    c。 打开项目MainWindow.xaml文件并粘贴此代码
    <Window x:Class="WpfApplication1.MainWindow"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:local="clr-namespace:WpfApplication1"
     Title="MainWindow" Height="350" Width="525">
     <Grid>
            <local:CustomPanel>
                <Rectangle Fill="Blue" local:CustomPanel.RequiredHeight="22"/>
                <Rectangle Fill="Red" local:CustomPanel.RequiredHeight="70"/>
                <Rectangle Fill="Green" local:CustomPanel.RequiredHeight="10"/>
                <Rectangle Fill="Purple" local:CustomPanel.RequiredHeight="5"/>
                <Rectangle Fill="Yellow" local:CustomPanel.RequiredHeight="42"/>
                <Rectangle Fill="Orange" local:CustomPanel.RequiredHeight="41"/>
            </local:CustomPanel>
        </Grid>
    </Window>
    

    关于c# - 自定义自动调整大小的WPF面板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3002656/

    相关文章:

    html - 如何强制我的自定义样式?

    java - 对于具有可重用内容/行为的 Web 应用程序,哪个 Java Web 框架是一个不错的选择?

    c# - Unity IoC - 单元测试类型注册是否正确

    c# - 访问 propertyinfo 中的属性

    c# - 洋葱架构 : Should we allow data annotations in our domain entities?

    .net - 用于 wpf mvvm 的 MVVM 工具包(模板)和 XAML powertoys 工作吗?

    c# - 为什么横向模式下的扩展布局在 Xamarin Forms 中显示半黑屏?

    c# - 从另一个 View 模型调用函数时 RaisePropertyChanged 不会触发

    wpf - WPF 中的可编辑数据网格

    c# - 将事件从自定义控件传播到窗体