WPF 使用纵横比调整用户控件的大小

Flo*_*ian 2 wpf resize aspect-ratio

我有一个 UserControl 并且必须使用纵横比调整 UserControl 的大小。这意味着:宽:高 = 2:1。目前我正在使用此代码:

    protected override Size ArrangeOverride(Size arrangeBounds)
    {
        if (ActualWidth == 0 || ActualHeight == 0) return arrangeBounds;
        base.ArrangeOverride(arrangeBounds);
        double ratio = 2;

        if (Parent != null)
        {
            var size = new Size(arrangeBounds.Height * ratio, arrangeBounds.Height);

            double containerWidth = ((FrameworkElement)Parent).ActualWidth;
            if (containerWidth < size.Width)
            {
                double newHeight = arrangeBounds.Height * (containerWidth / size.Width);
                canvas.Width = newHeight * ratio;
                canvas.Height = newHeight;
            }
            else
            {
                canvas.Width = size.Height * ratio;
                canvas.Height = size.Height;
            }
        }

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

但它并没有真正起作用。这意味着它有效,但不是每次都有效。如果我最大。它有时不会调整窗口大小,因此如果控件调整大小,它有点“随机”。因此,如果有人会有更好的解决方案,那会非常好。

Eth*_*gon 5

最直接的解决方案是通过值转换器将高度直接绑定到宽度。