Does anyone have an idea how to keep the Height/Width Ratio 1:1 of a UserControl?
E.g. if Height > Width, Width & Height will have the same size and vice versa.
Does anyone have an idea how to keep the Height/Width Ratio 1:1 of a UserControl?
E.g. 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
.
Try using a ViewBox and setting its Stretch property to Uniform
Another alternative:
<local:MyControl Width="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"/>
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