使Viewbox垂直缩放但水平拉伸

Joe*_*ite 16 wpf viewbox

我想创建一个仅扩展其高度的Viewbox(或类似的东西),然后水平拉伸其内容.

如果我这样做:

<Viewbox>
  <StackPanel>
    <Button>Foo</Button>
    <Button>Bar</Button>
  </StackPanel>
</Viewbox>
Run Code Online (Sandbox Code Playgroud)

然后我明白了:

http://www.excastle.com/misc/viewbox-center.png

它就好像两个按钮都具有Horizo​​ntalAlignment ="Center",然后缩放结果.但我不希望Horizo​​ntalAlignment ="Center"; 我想要Horizo​​ntalAlignment ="Stretch",像这样:

http://www.excastle.com/misc/viewbox-stretch.png

所以我希望它读取其内容的所需高度,仅根据高度计算缩放因子,然后允许缩放内容水平拉伸.

有没有办法使用Viewbox和/或某些第三方面板完成此操作?

Ric*_*key 16

WPF没有这样的控制,但你可以自己写一个没有太多麻烦.这是一个自定义的ViewboxPanel,它具有您的规格:

public class ViewboxPanel : Panel
{
    private double scale;

    protected override Size MeasureOverride(Size availableSize)
    {
        double height = 0;
        Size unlimitedSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
        foreach (UIElement child in Children)
        {
            child.Measure(unlimitedSize);
            height += child.DesiredSize.Height;
        }
        scale = availableSize.Height / height;

        return availableSize;
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        Transform scaleTransform = new ScaleTransform(scale, scale);
        double height = 0;
        foreach (UIElement child in Children)
        {
            child.RenderTransform = scaleTransform;
            child.Arrange(new Rect(new Point(0, scale * height), new Size(finalSize.Width / scale, child.DesiredSize.Height)));
            height += child.DesiredSize.Height;
        }

        return finalSize;
    }
}
Run Code Online (Sandbox Code Playgroud)

你像这样使用它:

<local:ViewboxPanel>
    <Button>Foo</Button>
    <Button>Bar</Button>
</local:ViewboxPanel>
Run Code Online (Sandbox Code Playgroud)

它肯定需要一些工作,但这可能会让你开始.