Eamonn McEvoy
Eamonn McEvoy

Reputation: 8986

Open View on button click MVVM

I know there are already a few questions like this but I can't seem to work out what to do, I have a button that I want to open a new Window, is there a way to do this in pure xaml? I don't see how I can open the dialog without either calling it from my CodeBehind or ViewModel. I am not using any mvvm toolkits for this.

Upvotes: 0

Views: 1668

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564831

I don't see how I can open the dialog without either calling it from my CodeBehind or ViewModel.

Typically, you do this in code - but, most MVVM frameworks provide a way to abstract this.

This is normally handled either via some form of service location (ie: injecting a "ViewService" or similar) in the ViewModel. The other option is to use some form of messaging, which is the approach of MVVM Light.

The advantage of these approaches is that the VM can be written without knowledge of the View still - you're changing the way you write your code around so that a command (in the ViewModel) triggers some event, and the correct View is opened for you. This keeps the View dependency out of your VM layer.

Upvotes: 4

Glory Raj
Glory Raj

Reputation: 17701

you can do like this....

You can use <x:Code>:

<Button Content="OK" Click="Button_Click"/>
<x:Code>
  private void Button_Click(object sender,RoutedEventArgs e)
  {
    MessageBox.Show("Hello");
  }
</x:Code>

The standard way to do this are commands.

Upvotes: 0

Related Questions