请问在WPF中如何快速计算出window上面的button位置的百分比?
请问在Visual Studio中如果把button拖到窗口上,如何让这个button的大小以及位置是以百分比来计算的,这样当窗体大小该百年时,button的大小和位置也会相应改变?
[解决办法]
因为你这个比例的依据可以有多种考量,最简单就是根据分配空间的百分比进行计算
MyButton
public class MyButton : Button { public MyButton() { HorizontalAlignment = System.Windows.HorizontalAlignment.Center; VerticalAlignment = System.Windows.VerticalAlignment.Center; } public double WidthPercentage { get { return (double)GetValue(WidthPercentageProperty); } set { SetValue(WidthPercentageProperty, value); } } public double HeightPercentage { get { return (double)GetValue(HeightPercentageProperty); } set { SetValue(HeightPercentageProperty, value); } } public static readonly DependencyProperty HeightPercentageProperty = DependencyProperty.Register("HeightPercentage", typeof(double), typeof(MyButton), new UIPropertyMetadata(0.0)); public static readonly DependencyProperty WidthPercentageProperty = DependencyProperty.Register("WidthPercentage", typeof(double), typeof(MyButton), new UIPropertyMetadata(0.0)); protected override Size MeasureOverride(Size constraint) { var result = new Size(constraint.Width * WidthPercentage, constraint.Height * HeightPercentage); return result; } protected override Size ArrangeOverride(Size arrangeBounds) { return base.ArrangeOverride(arrangeBounds); }}