使用元素子项移动网格

Move Grid with Element Children

我有如下代码

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Grid x:Name="one" Grid.Row="0"  Margin="49.667,15,15,15">
        <Grid x:Name="container1" Background="Red" Margin="10"/>
        <TextBlock Text="1"  FontSize="65" Margin="228,10,260,27"/>
    </Grid>

    <Button Content="mov" x:Name="first0" Click="first_Click" Foreground="White" HorizontalAlignment="Left" Margin="13.333,27.833,0,0" Width="29.334" Background="Black" Height="32" VerticalAlignment="Top"/>

    <Grid x:Name="due" Grid.Row="1" Background="black" Margin="49.667,15,15,15">
        <Grid x:Name="container2"  Margin="12,12,8,8" Background="#FF618F36"/>
        <TextBlock Text="2"  FontSize="65" Margin="228,10,198,27"/>
    </Grid>
</Grid>

以及后面的代码:

private static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
        if (child != null && child is T)
            return (T)child;
        else
        {
            T childOfChild = FindVisualChild<T>(child);
            if (childOfChild != null)
                return childOfChild;
        }
    }
    return null;
}

private void first_Click(object sender, System.Windows.RoutedEventArgs e)
{
    var first = FindVisualChild<Grid>(one);
    var second = FindVisualChild<Grid>(due);
    one.Children.Remove(first);
    due.Children.Remove(second);
    one.Children.Add(second);
    due.Children.Add(first);
}

使用此代码我可以移动网格 "one,due" 中的 "containers" 但是当我移动文本块时我不会那样做,因为将来这些网格将包括其他网格,文本框,文本块等,我问你是否有办法允许移动容器,包括儿童(文本框,文本块等)

预先感谢您的关注。

此致

@马克是对的。 TextBlock 位于 之上 您的容器网格,而不是它们内部,这就是它们不移动的原因。将您的 XAML 更改为此,它将按您期望的方式工作:

...
<Grid x:Name="one" Grid.Row="0"  Margin="49.667,15,15,15">
    <Grid x:Name="container1" Background="Red" Margin="10">
        <TextBlock Text="1"  FontSize="65" Margin="228,10,260,27"/>
    </Grid>
</Grid>

<Button ...

<Grid x:Name="due" Grid.Row="1" Background="black" Margin="49.667,15,15,15">
    <Grid x:Name="container2"  Margin="12,12,8,8" Background="#FF618F36">
        <TextBlock Text="2"  FontSize="65" Margin="228,10,198,27"/>
    </Grid>
</Grid>
...