WPF 控件能否以其父控件为中心,但也仅使用 xaml 尊重其同级控件的位置?

Can a WPF control be centered around its parent but also respect the position of its sibling control using xaml only?

我正在尝试将模态弹出式控件置于相对于整个屏幕的 xaml 屏幕的中央,但同时也让中央控件被同级(侧面板)推开如果控件太大,两者会相交。这对于代码隐藏、数据绑定、数据触发器、自定义控件和其他不太优雅的方法是可行的,但是有没有一种方法可以开箱即用地解决这个问题,只需要 xaml?

这是一个大大简化的问题版本,它是一个 window 有两个矩形的问题。橙色矩形始终为 200 像素。绿色矩形大小可变,但绝不会大于 600 像素。我们能否使绿色矩形在屏幕上居中,除非它足够宽以至于它会与橙色矩形发生碰撞,在这种情况下,绿色矩形位于橙色矩形的右侧(就像堆栈面板)?绿色和橙色的矩形可以放入任何你想要的容器中,容器可以任何你想要的方式嵌套。

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid Width="800">

            <Rectangle Width="200" Fill="Orange" HorizontalAlignment="Left" ></Rectangle>
            <Rectangle Width="300" Fill="Green" HorizontalAlignment="Center"></Rectangle>
    </Grid>
           
</Window>

没有内置方法可以执行此操作,但这种方法有效且相当简单:

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition MinWidth="200"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Rectangle Width="200" Fill="Orange" HorizontalAlignment="Left" /> 
        <Rectangle Grid.Column="1" Width="300" Fill="Green" HorizontalAlignment="Center"/>
    </Grid>

如果您不想复制橙色矩形的宽度,您可以这样做:

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition MinWidth="{Binding ElementName=OrangeRectangle, Path=ActualWidth}"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Rectangle x:Name="OrangeRectangle" Width="200" Fill="Orange" HorizontalAlignment="Left" /> 
        <Rectangle Grid.Column="1" Width="300" Fill="Green" HorizontalAlignment="Center"/>
    </Grid>