使用元素子项移动网格
本文关键字:移动 移动网 网格 元素 | 更新日期: 2023-09-27 18:36:07
我有如下代码
<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"中的"容器",但是当我移动文本块消失时,我不会那样做,因为将来这些网格将包括其他网格,文本框,文本块等,所以我问您是否有办法允许移动包括子项(文本框,文本块等)
提前感谢您的关注。
真诚地
@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>
...