WPF 将按钮从 StackPanel 移动到网格单元格不起作用

WPF move Button from StackPanel to Grid cell does not work

我有一个网格 (2x2) 和网格内的按钮。 我想以编程方式将 Button 从单元格 (0,0) 移动到单元格 (0,1)。

A:有效(以编程方式) 将 Button 从一个网格单元移动到另一个网格单元。

B:不起作用(以编程方式) 将 StackPanel 内的按钮移动到网格单元格。

C:有效(以编程方式) 将整个 StackPanel(里面有 Button)移动到另一个网格单元格

我能做什么?

<Window x:Class="CovidGamePrototype.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="1*" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="1*" />
    </Grid.ColumnDefinitions>

    <StackPanel  Name="stackPanel" Grid.Column="0" Grid.Row="0" Orientation="Vertical">
        <Button Name="btnTopLeft1"  Content="I am TopLeft 1" Height="Auto" />
        <Button Name="btnTopLeft2"  Content="I am TopLeft 2" Height="Auto" />
    </StackPanel>

    <Button Name="btnBottomLeft" Grid.Column="0" Grid.Row="1" Width="Auto" Content="I am BottomLeft" />
    <Button Name="btnTopRight" Grid.Column="1" Grid.Row="0" Content="I am TopRight" />
    <Button Name="btnBottomRight" Grid.Column="1" Grid.Row="1" Content="I am BottomRight"/>

</Grid>
 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        // does NOT work (move from left to right)
        // this Button is inside of a StackPanel
        Grid.SetColumn(btnTopLeft1, 1);
        Grid.SetZIndex(btnTopLeft1, 5);

        // works (move from left to right)
        Grid.SetColumn(btnBottomLeft, 1);
        Grid.SetZIndex(btnBottomLeft, 5);

        // works (move from left to right)
        // Grid.SetColumn(stackPanel, 1);
        // Grid.SetZIndex(stackPanel, 5);
    }
}

StackPanel 中删除 Button 并将 Button 插入到 StackPanel 的父级中,在您的情况下是 Grid

stackPanel.Children.Remove(btnTopLeft1);
var grid = (stackPanel.Parent as Grid);
grid?.Children.Add(btnTopLeft1);

Grid.SetColumn(btnTopLeft1, 1);
Grid.SetZIndex(btnTopLeft1, 5);