I have a Button
that closes my window when it's clicked:
<Button x:Name="buttonOk" IsCancel="True">Ok</Button>
That's fine until I add a Command
to the Button
i.e.
<Button x:Name="buttonOk"
Command="{Binding SaveCommand}"
IsCancel="True">Ok</Button>
Now it doesn't close presumably because I am handling the Command
. I can fix this by putting an EventHandler
in and calling this.Close()
i.e.
<Button x:Name="buttonOk"
Click="closeWindow"
Command="{Binding SaveCommand}"
IsCancel="True">Ok</Button>
but now I have code in my code behind i.e. the method SaveCommand
. I am using the MVVM pattern and SaveCommand
is the only code in my code behind.
How can I do this differently so as not to use code behind?
Very clean and MVVM way is to use
InteractionTrigger
andCallMethodAction
defined inMicrosoft.Interactivity.Core
You will need to add two namespaces as below
And Assemblies System.Windows.Interactivity and Microsoft.Expression.Interactions and then Below xaml code will work.
You don't need any code behind or anything else and can also call any other method of
Window
.I just completed a blog post on this very topic. In a nutshell, add an
Action
property to your ViewModel withget
andset
accessors. Then define theAction
from yourView
constructor. Finally, invoke your action in the bound command that should close the window.In the ViewModel:
and in the
View
constructor:Finally, in whatever bound command that should close the window, we can simply invoke
This worked for me, seemed like a fairly elegant solution, and saved me a bunch of coding.
I have following solution in Silverlight. Would also be in WPF.
ChildWindowExt.cs:
ItemWindow.xaml:
ItemViewModel.cs:
ItemsViewModel.cs:
MainPage.xaml:
I wish you all good ideas and projects ;-)
I also had to deal with this problem, so here my solution. It works great for me.
1. Create class DelegateCommand
2. Define your command
3. Bind your command in the view
4. And now the window
so thats it, you can also bind the command in the xaml file and find the window with FindAncestor and bind it to the command parameter.
For small apps, I use my own Application Controller for showing, closing and disposing windows and DataContexts. It's a central point in UI of an application.
It's something like this:
and their invocations from ViewModels:
Of course you can find some restrictions in my solution. Again: I use it for small projects, and it's enough. If you're interested, I can post full code here or somewhere else/
Unfortunately displaying windows is a real pain in MVVM so you need to do quite a bit of infrastructure work or use a MVVM framework like Cinch. If you want to invest the time to do it yourself here's a link of how Cinch does it.
Its good that you're trying to keep any logic out of the View but its really not the end of the world if you do. In this instance it doesn't sound like it would cause too many problems.