首页 > 解决方案 > 删除 XAML 元素的所有位置约束

问题描述

我正在构建一个 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" 尚未删除。如何通过代码删除该约束?

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

标签: c#xamluwp

解决方案


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

如果要删除RelativePanel.RightOf="_redRect",可以使用相同的方式RelativePanel.RightOf在代码中将 设置为 null 。

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

在此处输入图像描述


推荐阅读