【发布时间】:2017-07-04 14:01:42
【问题描述】:
我正在尝试显示一个与现有组件对齐的窗口。在此示例中,我想将其与按钮对齐。当我单击按钮时,我希望窗口自行定位,使其底部刚好在按钮上方,并且它的宽度与按钮相同。窗口左侧应与按钮左侧相同。
为了实现这一点,我使用以下 xaml:
<Window x:Class="WindowPositioningTest.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"
xmlns:local="clr-namespace:WindowPositioningTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Name="MyButton" Content="Click me to see window!" Width="300" Height="50" Click="Button_Click"/>
</Grid>
onclick 函数如下所示:
private void Button_Click(object sender, RoutedEventArgs e)
{
var window = new Window();
var myButtonLocation = MyButton.PointToScreen(new Point(0, 0));
window.Width = MyButton.ActualWidth;
window.Height = 300;
window.Left = myButtonLocation.X;
window.Top = myButtonLocation.Y - window.Height;
window.Show();
}
当我单击按钮时,会显示一个窗口,如下图所示。
我的问题是:为什么窗口没有按钮那么宽,为什么它不在正确的位置?就好像窗户周围有一个看不见的框架。
【问题讨论】:
-
看起来阴影是窗口的一部分
-
是的!所以它看起来。问题是我是否能以某种方式了解它的宽度,以便我可以相应地调整窗口的宽度和左位置。窗口宽度应与按钮相同。