I’m very new to MVVM and getting my first POC done now. However, I have been hitting my head to get one issue resolved for 2 days. Thought of explaining to you guys may help and resolve the issue so quickly. Let me brief my issue now. I have WPF MVVM application with a main View bound to MainViewModel. I have Textblock here to bind some content from the viewmodel while loading the screen which is working awesome. I also have ChildUserControl bound to ChildViewModel. Now, I need to bind different content to the Textblock in the main window from user control up on some action which is taking place in user control level. How it is possible ?
here is the sample code I have MainWindow.Xaml
<Window.Resources>
<viewModel:MainViewModel x:Key="mainWindowViewModel"/></Window.Resources>
<TextBlock Name="txtStatus" Text="{Binding StatusMessage, Mode=OneWay }"/>
ChildUserControl.xaml
<UserControl.Resources>
<viewModel:ChildModelView x:Key="ChildModelView"/> </UserControl.Resources>
public class ChildModelView : BaseViewModel
{
// Some child level logic..
// then need to update the txtStatus text block from parent
}
Your helps are much appreciated..!
I may be misunderstanding your needs here, but it sounds like you have a TextBlock in the MainWindow that needs to be updated in response to something that occurs in and with data supplied by the ChildWindow. Assuming that's what you're trying to do then I think there are a few different ways that you could do it. In particular, you could use an attached event.
http://msdn.microsoft.com/en-us/library/bb613550.aspx
The technical explanation is a bit lengthy, so I'll leave it to MSDN to do that, but the short explanation is simply that it's just an event that will be raised from your child window and handled by your MainWindow. The bonus here is that it will pass in your ChildWindowViewModel as the DataContext.
An easy way to achieve this would be to use IoC. When you create your child view model, pass a reference of your main view model to your child viewmodel , and hold it as a private read only variable. You now access all of your main VM publics .
An alternative solution would ppossibly be to use the Mediator pattern.
Knocked up a simple App to demonstrate IoC solution.
App.xaml.cs
MainWindowViewModel.cs
ChildWindowViewModel.cs
ViewModelBase.cs
DelegateCommand.cs
MainWindow.xaml
ChildWindow.xaml
Image before clicking on update status
Image after clicking on updatestatus