删除XAML元素的所有位置限制

时间:2019-05-22 16:10:45

标签: c# xaml uwp

我正在构建UWP应用。我使用的Rectangle XAML元素已在XAML代码中指定了定位属性RelativePanel.RightOf()。现在单击特定按钮,我需要将Rectangle从其原始位置移到其他控件的左侧。因此,在收到Click事件后,我使用属性RelativePanel.SetLeftOf()将其移动。

XAML代码-

    <StackPanel>
        <RelativePanel Height="50" Width="200">
            <Rectangle x:Name="_redRect" Height="50" Width="50" Fill="Red" RelativePanel.AlignLeftWithPanel="True"/>
            <Rectangle x:Name="_blueRect" Height="50" Width="50" Fill="Blue" RelativePanel.RightOf="_redRect"/>
            <Rectangle x:Name="_greenRect" Height="50" Width="50" Fill="Green" RelativePanel.AlignRightWithPanel="True"/>
        </RelativePanel>
        <Button x:Name="_switch" Click="OnSwitchClicked">Switch</Button>
    </StackPanel>

C#代码-

    private void OnSwitchClicked(object sender, RoutedEventArgs e)
    {
        RelativePanel.SetLeftOf(_blueRect, _greenRect);
    }

但这不能解决我的问题。 _blueRect似乎位于_redRect和_greenRect的中间。这可能是因为尚未删除第一个约束RelativePanel.LeftOf =“ _redRect”。如何通过代码删除该约束?

还有什么方法可以一起消除所有定位约束?

1 个答案:

答案 0 :(得分:1)

  

这可能是因为尚未删除第一个约束RelativePanel.LeftOf =“ _redRect”。如何通过代码删除该约束?

如果要删除RelativePanel.RightOf="_redRect",则可以使用相同的方法将RelativePanel.RightOf设置为空。

private void OnSwitchClicked(object sender, RoutedEventArgs e)
{
    RelativePanel.SetLeftOf(_blueRect, _greenRect);
    RelativePanel.SetRightOf(_blueRect, null);
}

enter image description here