有谁知道如何保持 UserControl 的高度/宽度比为 1:1?
例如,如果高度 > 宽度,宽度和高度将具有相同的大小,反之亦然。
有谁知道如何保持 UserControl 的高度/宽度比为 1:1?
例如,如果高度 > 宽度,宽度和高度将具有相同的大小,反之亦然。
我不确定这是否可行,但如果您为SizeChanged
事件注册一个处理程序并在其中放入您的代码,请保持纵横比为 1:1。
该SizeChangedEventArgs
参数具有旧大小和新大小,因此您可以检查哪个已更改并相应地更新另一个。
您可能需要引入一个保护变量,这样您就不会因为更新or而得到级联SizeChanged
事件。Height
Width
另一种选择:
<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 事件的用户控件中使用此代码:
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;
}
}
也许这有帮助......干杯