0

I want to show a window for some inputs on the click of a button. The window should be placed right below the button (green circle is the button, white is the new window):

enter image description here

How do I get the location of the button to set the location of the new window in MVVM?

I have the button in the view like this:

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

The command in the viewmodel:

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

Binding the location of the button to the VM and then sending it to the new windows might be a solution, but is it a good one?

el-nino
  • 399
  • 9
  • 26

1 Answers1

0

You could retrieve the relative position of the Button in the view using the TransformToAncestor method: Get Absolute Position of element within the window in wpf.

You could either do this in the code-behind of the view or in an attached behaviour (https://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF), before you invoke the command of the view model.

Once you have the coordinates, you could pass these as a parameter to the command:

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);
}
mm8
  • 163,881
  • 10
  • 57
  • 88