Click here to Skip to main content
Click here to Skip to main content
Go to top

Open Child Window in MVVM environment

, 14 May 2012
Rate this:
Please Sign up or sign in to vote.
How to open pop up window in MVVM environment. You can use it in WPF or Silverlight.

In This post I am going to demonstrate how you can use child windows in MVVM environment as well as how you can pass data to child window or can share same viewmodel and on Close refresh the parent window. I found this approach pretty simple and straight forward. Other approaches are using toolkit or other third party components. You can also create object of child window from viewmodel but then it breaks the MVVM rule. In forums I have found lot of people are struggling and confused for best possible simplest MVVMish approach. So here you go.

Where we need child window

In commercial Silverlight applications opening child window for detail or other user inputs is the most user-friendly approach so avoiding child window can be bit costly.

Background

To implement this application, I am going to use the following technologies:

  • Silverlight5 for the client tier
  • Visual Studio 2010

Silverlight Business Application

Create new Silverlight business application. Name it to ‘WindowWithMVVM’.

Silverlight Client

Create ViewModel folder. Add viewmodel class for parent view. Name it as ‘HomeViewModel.cs’.

I am going to inherit viewmodel from ‘INotifyPropertyChanged’. So that it can notify view for property changes. Now time to create property which can be shared across child window and parent view and bind to textbox in both windows. If you modify text in child window you can see in parent window. This is very simple scenario but off course you can achieve most complex business scenarios using grid or list etc.

Code for Viewmodel:

public class HomeViewModel : INotifyPropertyChanged
{
    public HomeViewModel()
    {
    }
    private string _UserInput;
    public string UserInput
    {
        get
        {
            return this._UserInput;
        }
        set
        {
            if (this._UserInput != value)
            {
                this._UserInput = value;
                this.NotifyPropertyChanged("UserInput");
            }
        }
    }
    protected void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
} 

Modify Home page to add textbox and button. On button click I am going to open childwindow.

<StackPanel x:Name="ContentStackPanel" Style="{StaticResource ContentStackPanelStyle}">
    <TextBlock x:Name="HeaderText" Style="{StaticResource HeaderTextStyle}" 
        Text="{Binding Path=Strings.HomePageTitle, Source={StaticResource ApplicationResources}}"/>
    <Grid Height="281" Width="555" HorizontalAlignment="Center">
        <StackPanel Orientation="Vertical">
            <TextBox Height="156" HorizontalAlignment="Left" Name="textBox1" Text="{Binding UserInput, Mode=TwoWay}" AcceptsReturn="True" IsEnabled="False" VerticalAlignment="Top" Width="554" />
            <Button Height="23" Name="button1" Content="Modify in Child Window" Width="150" Click="button1_Click" />
        </StackPanel>
    </Grid>
</StackPanel>

In resorce section of page add datacontext. Off course you need to add viewmodel reference.

<navigation:Page.DataContext>
    <vm:HomeViewModel UserInput="Base User Input. You can modify me in child window." />
</navigation:Page.DataContext>

In Codebehind code I am opening child window and onclose showing message. But you can do more stuff like collect object, saving something or changing status.

private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
{
    var window = new ChildWindow1 { DataContext = this.DataContext };
    window.Unloaded -= new System.Windows.RoutedEventHandler(ChildWindow_Unloaded);
    window.Unloaded += new System.Windows.RoutedEventHandler(ChildWindow_Unloaded);
    window.Show();
}
void ChildWindow_Unloaded(object sender, System.Windows.RoutedEventArgs e)
{
    //You can do child window closing coding here like collect object, saving something or changing status
    MessageBox.Show("Child window is closed now.");
}

Add new child window as ‘ChildWindow1.xaml’ in view folder.

Add textbox in XAML and bind it to ‘UserInput’ property. This is the property which we have defined in viewmodel and also bound to parent view textbox.

<TextBox Height="146" HorizontalAlignment="Left" Margin="29,57,0,0" Name="textBox1" Text="{Binding UserInput, Mode=TwoWay}" AcceptsReturn="True" VerticalAlignment="Top" Width="321" /> 

Now I think we are all set to run the project. After running, click on home page button to open child window. In child window you can modify the text and click ok. You can see updated text in parent view.

Summary

In this Article you have learned how you can use window in Silverlight/WPF projects without breaking MVVM rules. Hope this would be pretty simple example to elaborate scenario.

If this article helps you in designing/coding application don’t forget to hit voting option. Please comment your suggestions and improvements so others can benefit. My Other Articles Link.

Happy Coding!!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ManojKumar19
Architect
United States United States
Manoj Kumar
 
Architect, Lead Software Engineer and Senior BI Developer | Microsoft Certified Technology Specialist(MCTS) | Exp in C#, Silverlight, WPF, WCF, WF, ASP.Net 4, MVC4, Razor View Engine and EF Code First, SSRS, SSAS, SSIS, ETL, SQL Server, Usability/User Experience, HTML5, CSS3, Javascript etc.
 
He lives with his wife Supriya and daughter Tisya in Bay Area.

Comments and Discussions

 
QuestiondilogResult using mvvm [modified] Pinmemberaudil mohammed25-Jul-13 19:09 
SuggestionRe: dilogResult using mvvm PinmemberWiiMaxx14-Jul-14 4:54 
GeneralMy vote of 2 PinmemberMember 91619834-Dec-12 6:15 
QuestionIf it's so simple, why is your example code so complex? PinmemberMember 91619834-Dec-12 6:14 
GeneralMy vote of 1 PinmemberGerrard57528-Nov-12 8:33 
GeneralMy vote of 1 PinmemberMember 91619835-Oct-12 23:05 
GeneralRe: My vote of 1 PinmemberManojKumar198-Oct-12 12:09 
GeneralMy vote of 2 Pinmembereddy morrison22-May-12 2:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 14 May 2012
Article Copyright 2012 by ManojKumar19
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid