我有以下代码
<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);
}
使用此代码,我可以移动网格中的“容器”“一个,到期”,但是当我移动文本块消失然后我不会那样,因为将来这些网格将包括其他网格,文本框,文本块等等我问你是否有办法允许移动容器,包括儿童(文本框,文本块等)。
提前感谢您的关注。
此致
答案 0 :(得分:1)
@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>
...