【发布时间】:2016-08-29 07:09:07
【问题描述】:
我有一个 WPF 应用程序,我正在尝试正确定位元素。只有四个元素,所以它应该很简单,但我就是无法让它发挥作用。
一个问题是窗口会在出现时将自身调整为(大约)桌面窗口的大小,因此它没有固定大小。
元素应该从上到下堆叠,所以 Stack Panel 看起来很自然。但是第三个元素必须占用顶部两个和底部不占用的所有剩余空间。无论我尝试什么,它要么占用太多空间,要么太少。如果我给它一个具体的像素大小,我似乎只能让它工作,如上所述,这是行不通的。
我尝试过的最新产品是 Dock Panel。虽然它在 Visual Studio 设计器中看起来是正确的,但在执行时,第三个元素(画布)完全覆盖了底部元素。
我的 XAML:
<DockPanel>
<Button x:Name="btnClose" DockPanel.Dock="Top" Content="X"
HorizontalAlignment="Right" Margin="0,5,5,0" VerticalAlignment="Top"
Width="Auto" Height="Auto" Background="Black"
Foreground="White" Click="btnClose_Click"/>
<Label x:Name="lblTitle" DockPanel.Dock="Top" Content="My Title"
HorizontalAlignment="Center" VerticalAlignment="Top" Width="Auto"
Foreground="White" FontWeight="Bold" FontSize="22"/>
<Label x:Name="lblControls" DockPanel.Dock="Bottom" Content="Placeholder"
HorizontalAlignment="Center" VerticalAlignment="Bottom" Width="Auto"
Height="Auto" Foreground="White" FontWeight="Bold" FontSize="22"/>
<Border x:Name="CanvasBorder" BorderBrush="White" BorderThickness="5" >
<Canvas x:Name="cvsChart" Grid.Row="0" HorizontalAlignment="Stretch"
VerticalAlignment="Top" Width="Auto">
</Canvas>
</Border>
</DockPanel>
知道如何让 Canvas 拉伸并填充其他三个不占用的所有空间吗?
更新 由于@Peter Duniho 几乎向我证明了代码有效,因此我尝试了一个实验并删除了我在窗口出现时调整大小的代码。把它拿出来,窗口完全正确地出现了。这就是我将其调整为(主要)桌面大小的方法:
public const int WINDOW_OFFSET = 10;
...
int screenWidth = (int)System.Windows.SystemParameters.PrimaryScreenWidth;
int screenHeight = (int)System.Windows.SystemParameters.PrimaryScreenHeight;
// center this window in desktop
Width = screenWidth - WINDOW_OFFSET;
Height = screenHeight - WINDOW_OFFSET;
Left = WINDOW_OFFSET/2;
Top = WINDOW_OFFSET/2;
所以我四处摸索,并在“堆栈”上找到了一条评论,该评论说要获取 WorkArea 而不是 PrimaryScreenHeight。我试过了,瞧!,整个应用程序窗口出现了。
int screenWidth = (int)System.Windows.SystemParameters.WorkArea.Width;
int screenHeight = (int)System.Windows.SystemParameters.WorkArea.Height;
事实证明,底行正在显示,我只是看不到它,因为它出现在屏幕底部下方。现在我可以看到了,我又回到了开发天堂!
感谢大家的意见!
【问题讨论】: