首页 > 解决方案 > C# UWP 按钮没有按照我想要的方式对齐

问题描述

我在“开始”按钮旁边创建了一个按钮。在我的 xaml 页面中,按钮出现在我想要的位置。

在此处输入图像描述

但是,当我运行该应用程序时,它会出现在随机位置。

在此处输入图像描述

我该如何解决 ?

StackPanel>
        <TextBlock Text="Description:" Style="{StaticResource SampleHeaderTextStyle}"/>
        <TextBlock Style="{StaticResource ScenarioDescriptionTextStyle}" Text="This page is where your exercise starts " FontSize="20"/>
        <TextBlock TextWrapping="Wrap" Margin="0,20,0,0" FontSize="20">
            Follow the instruction and press "Start" to begin the exercise.
        </TextBlock>
        <TextBlock TextWrapping="Wrap" Margin="0,0,0,0" FontSize="15">
            (Ensure the connected BLE device is working before starting the exercise.)
        </TextBlock>
        <TextBlock x:Name="txtClock" TextWrapping="Wrap" Margin="0,10,0,0" FontSize="20"/>
        <Button x:Name="btnStart" Content="Start" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,10,0,0" Height="38" Width="106" Click="btnStart_Click_1"/>
        <TextBlock x:Name="txtExercise"  TextWrapping="Wrap" Margin="0,10,0,0" FontSize="15"/>
        <TextBlock x:Name="txtAngle"  TextWrapping="Wrap" Margin="0,10,0,0" FontSize="15"/>
        <TextBlock x:Name="txtDisplay"  TextWrapping="Wrap" Margin="0,10,0,0"/>
        <TextBlock x:Name="txtAgain" Text="" TextWrapping="Wrap" Margin="0,10,0,0" FontSize="15"/>
        <Button x:Name="btnRefresh" Content="Refresh" HorizontalAlignment="Left" VerticalAlignment="Top" Height="38" Width="106" Margin="150,-158,0,0" Click="btnRefresh_Click"/>

标签: c#uwp

解决方案


由于您使用的Margin-Property是按钮,因此它会在其他地方弹出是有道理的。

老实说,我真的不知道为什么,但我遇到了同样的问题。

我建议您使用RelativePanelaStackPanel或 a Grid

你可以在这个微软页面上阅读。了解更多关于各种类型之间的差异。

网格看起来像这样:(请记住,网格的索引为 0)

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="100"/> //For a Row of 100 units height
    <RowDefinition Height="*"/> //For a Row which fills the rest of the available screen space
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="100"/> //For a column of 100 units width
    <ColumnDefinition Width="*"/> //For a column which fills the rest of the screen
  </Grid.ColumnDefinitions>

  <Button x:Name="Button1" Grid.Row="0" Grid.Column="0" />
  <Button x:Name="Button2" Grid.Row="1" Grid.Column="1" />
</Grid> 

Stackpanel 看起来像这样:(这里要记住的是,当屏幕/窗口大小发生变化时,Stackpanel 不会调整其元素的大小)

<Stackpanel Orientation="horizontal">
  <Button x:Name="Button1"/>
  <Button x:Name="Button2"/>
</Stackpanel>

推荐阅读