2

有谁知道如何保持 UserControl 的高度/宽度比为 1:1?

例如,如果高度 > 宽度,宽度和高度将具有相同的大小,反之亦然。

4

5 回答 5

7

我不确定这是否可行,但如果您为SizeChanged事件注册一个处理程序并在其中放入您的代码,请保持纵横比为 1:1。

SizeChangedEventArgs参数具有旧大小和新大小,因此您可以检查哪个已更改并相应地更新另一个。

您可能需要引入一个保护变量,这样您就不会因为更新or而得到级联SizeChanged事件。HeightWidth

于 2009-11-18T12:19:30.697 回答
7

另一种选择:

<local:MyControl Width="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"/>
于 2015-01-29T13:35:57.937 回答
5

尝试使用 ViewBox 并将其 Stretch 属性设置为 Uniform

于 2011-05-08T07:25:24.307 回答
0

我用这个代码来保持纵横比

在 usercontrol 内部全局定义 org_width, org_height, org_ratio :

private static double org_width = 77.6;//desired width
private static double org_height = 81.4;//desired height

private static double org_ratio = org_width / org_height;

在 SizeChanged 事件的用户控件中使用此代码:

FrameworkElement UCborder = this;
UCborder.Width = UCborder.Height*org_ratio;

最后你的用户控制代码应该是这样的:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace yournamespace
{
    public partial class YourUserControl : UserControl
    {

      private static double org_width = 77.6;//desired width
      private static double org_height = 81.4;//desired height

     private static double org_ratio = org_width / org_height; // width/height



     public YourUserControl()
     {
         InitializeComponent();
     }


     private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
     {
          FrameworkElement UCborder = this;
          UCborder.Width = UCborder.Height*org_ratio;
     }
  }
}

祝你好运

于 2015-03-11T07:24:09.693 回答
-2
private bool isSizeChangeDefered;

 private void uiElement_SizeChanged(object sender, SizeChangedEventArgs e)
    {
         //Keep Acpect Ratio
        const double factor = 1.8;
        if(isSizeChangeDefered)
            return;

        isSizeChangeDefered = true;
        try
        {
            if (e.WidthChanged)
            {
                driverPan.Height = e.NewSize.Width * factor; 
            }
            if (e.HeightChanged)
            {
                driverPan.Height = e.NewSize.Width / factor; 
            }
        }
        finally
        {
        //    e.Handled = true;
            isSizeChangeDefered = false;
        }
    }

也许这有帮助......干杯

于 2011-05-05T16:18:47.620 回答