在MVVM中点击的按钮的位置打开弹出窗口或窗口

问题描述:

我想在点击按钮时显示一些窗口。窗口应正下方的按钮被放置(绿圈是按钮,白色是新窗口):在MVVM中点击的按钮的位置打开弹出窗口或窗口

enter image description here

如何获得按钮的位置设定在新窗口中的位置MVVM?

我在这样的视图中的按钮:

<Button Command="{Binding LoginCommand}"/> 

在视图模型的命令:

private void ExecuteLoginCommand() 
{ 
    var dialog = new UserLogin(); 
    dialog.ShowDialog(); 
} 

绑定按钮VM的位置,然后将其发送到新窗户可能是一个解决方案,但它是一个很好的?

您可以使用TransformToAncestor方法检索Button在视图中的相对位置:Get Absolute Position of element within the window in wpf

在调用视图模型的命令之前,您可以在视图的代码隐藏或附加行为(https://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF)中执行此操作。

一旦你的坐标,你可以通过这些作为参数的命令:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    Button button = sender as Button; 
    Point relativePoint = button.TransformToAncestor(this).Transform(new Point(0, 0)); 

    var vm = DataContext as YourViewModel; 
    //pass the Point itself or create a custom class yourself and pass an instance of this one here 
    vm.LoginCommand.Execute(relativePoint); 
}