簡體   English   中英

使用子元素移動網格

[英]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”中移動“容器”,但是當我移動textblock消失時,我不會那樣做,因為將來這些網格將包括其他Grid,TextBox,textblock等,所以請問您是否有辦法允許移動包括子容器(文本框,文本塊等)的容器

預先感謝您的關注。

誠摯

@Mark是正確的。 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>
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM