Reputation: 121
Im building an app trying to follow MVVM as far as possible. Its an windows 8 store app and Im using MVVM-light. Now let say I have a MainPage using MainViewModel and I also have a UserControl using UserViewModel.
Now I want to be able to communicate between MainPage and UserControl without using any code-behind. In this simple scenario i would like to "click" a button in my UserControl
from a button in MainPage
MainPage.Xaml:
Here I have a button with which I wish to click a button in the Usercontroll
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button Content="MyButton"
Command="MyCommand"></Button>
</Grid>
MainPageViewModel:
public class MainViewModel : ViewModelBase
{
//
}
UserControll.Xaml Here is the button I wish to click from MainPage
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button Content="UcButton"/>
</Grid>
UserControlViewModel:
public class UserControlViewModel : ViewModelBase
{
//
}
Im interested in knowing about how you can interact with UI-Elements following the MVVM-pattern. Any links or tips appreciated.
Upvotes: 0
Views: 79
Reputation: 2778
I can't comment since I don't have enough points, and the question seems a bit weird. Do you want to click the button so that it shows in the GUI, like the button turns blue or do you want to invoke a command in usercontrolViewModel. If it is the latter you could maybe do a fix like this:
MainPage.xaml
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button Content="MyButton"
Command="{Binding UserControlViewModel.SomeUserControlCommand, Source={StaticResource Locator}}"></Button>
</Grid>
Remember to check what name you gave UserControlViewModel in the ViewModelLocator and you will of course have to create the command: SomeUserControlCommand in UserControlViewModel.
Upvotes: 1
Reputation: 50672
The 'clean' (MVVM way) of doing this is by having the ViewModels interact.
So if View1 should invoke something in View2 have View1 trigger a Command on its ViewModel1. ViewModel1 should then contact ViewModel2. ViewModel2 would executed the required action and show the result through its properties. View2 will bind to the properties and show the effect of the action.
Interaction between ViewModels can be done through a publisher-subscriber model (message broker, bus, ...) In MVVM-light there is a Messenger class to keep the dependencies clean.
Upvotes: 1