0
我有這樣的代碼如下移動網格元素孩子
<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);
}
有了這個代碼,我可以在網格「一個移動的「容器」,因「但是當我移動文本塊消失,那麼我不會那樣做,因爲將來這些網格將包括其他網格,文本框,文本塊等,所以我問你是否有一種方法來允許移動包括兒童的容器(文本框,textblock等)
非常感謝您的關注。
真誠
一樣,可能不是做正確的方式它。你真的想做什麼? –
@HighCore我只是想在網格(one和due)之間移動網格(容器1和容器2)與包含的所有Child元素,在這種情況下,我只在網格(容器1和容器2)內放置一個TextBlock,但實際上包含更多的元素,所以我的代碼我可以移動容器,但是當我移動位於內部的TextBlock消失。希望你明白了。謝謝你 – JayJay
這不是我問的。我的問題真的是你想要做什麼?在WPF中,你不會抓住可視樹的片斷並移動它們,沒有「好」的理由,你想要實現什麼樣的UI或效果? –