![](/img/trans.png)
[英]Why does a WPF ComboBox height expand to fill a grid cell, but not in a StackPanel?
[英]WPF move Button from StackPanel to Grid cell does not work
我有一个网格(2x2)和网格内的按钮。 我想以编程方式将按钮从单元格(0,0)移动到单元格(0,1)。
答:可以(以编程方式)将按钮从一个网格单元移动到另一个网格单元。
B:不起作用(以编程方式)将 StackPanel 内的按钮移动到网格单元格。
C:是否工作(以编程方式)将整个 StackPanel(内部带有按钮)移动到另一个网格单元
我能做些什么?
<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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.