简体   繁体   中英

How to keep the aspect ratio of a UserControl?

Does anyone have an idea how to keep the Height/Width Ratio 1:1 of a UserControl?

Eg if Height > Width, Width & Height will have the same size and vice versa.

I'm not sure this will work, but if you register a handler for the SizeChanged event and in there put in your code keep the aspect ratio 1:1.

The SizeChangedEventArgs argument has the old size and the new size so you can check which has changed and update the other accordingly.

You might need to introduce a guard variable so that you don't get a cascade of SizeChanged events as a result of updating the Height or Width .

另一种选择:

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

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

i used this code for keeping aspect ratio

inside usercontrol globally define 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;

use this code inside usercontrol in SizeChanged event:

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

and finally your user control code should looks like this:

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

good luck

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

maybe this helps... cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM