XAML c#获取窗口位置

时间:2015-07-17 04:22:06

标签: position window location

XAML C#的程序员如何找到wpf应用程序窗口的当前位置?有一个函数可以找到启动位置,但至关重要的是,当通过将窗口拖动到另一侧来移动窗口时,位置会发生变化,所以我总是需要当前位置,以便另一个函数相对于wpf窗口位置起作用。

2 个答案:

答案 0 :(得分:1)

我不确定如何找到窗口位置但是使用光标我已经完成它来查找当前位置,可能是可以指导你的。要知道光标的当前位置,你应该在窗口内,否则它总是显示0,0。代码是这样的:

Xaml文件:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Application 2" Height="350" Width="325"
        MouseDown="Window_MouseDown"
        AllowDrop="True" DragOver="Window_DragOver">
    <StackPanel>
        <Label Name="lblInfo1" Content="Info 1"/>
        <Label Name="lblInfo2" Content="Info 2"/>
    </StackPanel>
</Window>

C#文件:

private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
    DragDrop.DoDragDrop((DependencyObject)e.Source, "Sample", DragDropEffects.Copy);
}

private void Window_DragOver(object sender, DragEventArgs e)
{
    System.Windows.Point p1 = Mouse.GetPosition(this);
    lblInfo1.Content = string.Format("Mouse.GetPosition: {0}, {1}", p1.X, p1.Y);

    System.Windows.Point p2 = e.GetPosition(this);
    lblInfo2.Content = string.Format("DragEventArgs.GetPosition: {0}, {1}", p2.X, p2.Y);
}

试试吧。

答案 1 :(得分:0)

对于带有事件的代码隐藏绑定按钮:

private void b_Click(object sender, EventArgs e)
{
    // your code...
}

Xaml文件:

<Button Click="ButtonClicked">Button</Button>