我正在尝试在窗口显示之前计算StackPanel
width
,height
(位于网格的中间单元格中)(例如在窗口构造函数中)。如何实现?
<Window x:Class="WpfApplication2.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow" Height="300" Width="300">
<Grid Name="grid">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Grid.Row="1" Grid.Column="1" Name="stackPanel"></StackPanel>
</Grid>
窗口测量也与stackPanel设置DesiredSize
到{0;0}
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
this.Measure(new Size(this.Width, this.Height)); // -> this.DesiredSize = {0;0}
...
}
}
EDIT1
以下适用于FixedPage:
fixedPage.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
fixedPage.Arrange(new Rect(0, 0, fixedPage.DesiredSize.Width, fixedPage.DesiredSize.Height));
然后我们可以访问stackPanel.ActualWidth
和stackpanel.ActualHeight
。
但对于Window,它不起作用。
答案 0 :(得分:1)
尝试Loaded
事件:
public TestWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(TestWindow_Loaded);
}
void TestWindow_Loaded(object sender, RoutedEventArgs e)
{
//this.DesiredSize shouldnt be {0,0} now
}
编辑:由于StackPanel
已经占用最大Size
,即使其中没有任何内容,其SizeChanged
事件也只会如果您添加了很多项目,则会被解雇,因此您可以使用SizeChanged
这样的StackPanel
事件:
private void spTest_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (!(e.PreviousSize.Height == 0 && e.PreviousSize.Width == 0)) //will also be fired after loading
{
//Create another Page
}
}
EDIT2:另一种可能的解决方案:
public MainWindow()
{
InitializeComponent();
yourStackPanelName.Loaded += new RoutedEventHandler(yourStackPanelName_Loaded);
}
void yourStackPanelName_Loaded(object sender, RoutedEventArgs e)
{
double height = ((StackPanel)sender).ActualHeight;
double width = ((StackPanel)sender).ActualWidth;
}