如何以编程方式定位按钮 - UWP

时间:2017-12-13 04:15:34

标签: c# xaml uwp

我想以编程方式在屏幕右下方放置一个按钮。按钮应放置在屏幕高度和宽度的25%处(右下角)。如何以编程方式完成?

var displayInformation = DisplayInformation.GetForCurrentView();
ScreenHeight= (int)displayInformation.ScreenHeightInRawPixels;//1080
ScreenWidth= (int)displayInformation.ScreenWidthInRawPixels;//1920

  <Button x:Name="btnTest"   VerticalAlignment="Bottom">

1 个答案:

答案 0 :(得分:1)

根据您的评论,您需要距离右下角的距离。您可以通过设置按钮的边距并设置对齐来实现这一点 要根据应用程序/页面大小设置边距,可以使用以下代码段:

public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.SizeChanged += MainPage_SizeChanged;
        }

        private void MainPage_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var height = this.ActualHeight;
            var width = this.ActualWidth;

            btnTest.Margin = new Thickness(0, 0, 0.25 * width, 0.25 * height);
        }
    }

您可以在MainPage_SizeChanged

中设置对齐方式
btnTest.VerticalAlignment = VerticalAlignment.Bottom;
btnTest.HorizontalAlignment = HorizontalAlignment.Right;

另一种选择是在xaml中设置对齐:

<Button x:Name="btnTest" Content="Test" VerticalAlignment="Bottom" HorizontalAlignment="Right"/>