簡體   English   中英

如何保持UserControl的長寬比?

[英]How to keep the aspect ratio of a UserControl?

有誰知道如何保持UserControl的高寬比1:1?

例如,如果“高度”>“寬度”,則“寬度和高度”將具有相同的大小,反之亦然。

我不確定這是否行得通,但是如果您為SizeChanged事件注冊一個處理程序,然后在其中放入代碼,則將寬高比保持為1:1。

SizeChangedEventArgs參數具有舊大小和新大小,因此您可以檢查哪個已更改並相應地更新另一個。

您可能需要引入一個保護變量,以免由於更新HeightWidth導致級聯的SizeChanged事件。

另一種選擇:

<local:MyControl Width="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"/>

嘗試使用ViewBox並將其Stretch屬性設置為Uniform

我用這段代碼來保持寬高比

在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事件的usercontrol中使用以下代碼:

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;
     }
  }
}

祝好運

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;
        }
    }

也許有幫助...干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM