gpt4 book ai didi

.net - 如何在窗口显示前计算 ActualWidth ActualHeight

转载 作者:行者123 更新时间:2023-12-04 16:50:30 24 4
gpt4 key购买 nike

我正在尝试在窗口显示之前计算 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>

Window 的测量也和 stackPanel 一样将 DesiredSize 设置为 {0;0}

public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();

this.Measure(new Size(this.Width, this.Height)); // -> this.DesiredSize = {0;0}

...

}
}

编辑1

以下适用于 FixedPage:

fixedPage.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); 
fixedPage.Arrange(new Rect(0, 0, fixedPage.DesiredSize.Width, fixedPage.DesiredSize.Height));

然后我们可以访问 stackPanel.ActualWidthstackpanel.ActualHeight

但是对于Window,它不起作用。

最佳答案

尝试 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 事件只会在您添加很多项时触发,因此您可以像这样使用 StackPanelSizeChanged 事件:

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;
}

关于.net - 如何在窗口显示前计算 ActualWidth ActualHeight,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13835690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com