Click here to Skip to main content
15,867,704 members
Articles / Programming Languages / C#

Open Child Window in MVVM environment

Rate me:
Please Sign up or sign in to vote.
4.56/5 (10 votes)
14 May 2012CPOL2 min read 60.2K   1.7K   12   10
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’.

Image 1

Silverlight Client

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

Image 2

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:

C#
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.

XML
<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.

XML
<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.

C#
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.

Image 3

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.

XML
<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.

Image 4

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)


Written By
Architect
United States United States
Manoj Kumar

AWS Certified Solutions Architect (Web development, Serverless, DevOps, Data)
MSSE - Cloud and Mobile Computing, San Jose State University

A wide range of experience in resolving complex business problems.

* Cloud Technologies: EC2, S3, DynamoDB & RDS databases, Lambda serverless architecture, Microservices architecture, API Gateway, Cloud Front CDN, Linux/Windows systems administration, CloudFormation, DevOps, Docker, CICD, Node.js, Python, Java and other open source technologies. Familiarity with OpenStack.
* Web Technologies: HTML5, Node.Js, MEAN Stack, AngularJS, ASP.Net Core, MVC5, CSS3, jQuery, Bootstrap, MongoDB, JavaScript, JSON, AJAX.
* Data: Experience in database architecture, Big Data, Machine Learning, BI, Data Analytics, No-SQL databases, ETL.
* Mobile: IOS/Android app development

He lives with his wife Supriya and daughter Tisya in Bay Area.

Comments and Discussions

 
QuestionMisses the point of MVVM Pin
Martin00027-Jun-15 6:17
Martin00027-Jun-15 6:17 
GeneralMy vote of 5 Pin
TheRealSteveJudge14-Jan-15 4:41
TheRealSteveJudge14-Jan-15 4:41 
QuestiondilogResult using mvvm Pin
audil mohammed25-Jul-13 19:09
audil mohammed25-Jul-13 19:09 
SuggestionRe: dilogResult using mvvm Pin
WiiMaxx14-Jul-14 4:54
WiiMaxx14-Jul-14 4:54 
GeneralMy vote of 2 Pin
Member 91619834-Dec-12 6:15
Member 91619834-Dec-12 6:15 
QuestionIf it's so simple, why is your example code so complex? Pin
Member 91619834-Dec-12 6:14
Member 91619834-Dec-12 6:14 
GeneralMy vote of 1 Pin
Gerrard57528-Nov-12 8:33
Gerrard57528-Nov-12 8:33 
GeneralMy vote of 1 Pin
Member 91619835-Oct-12 23:05
Member 91619835-Oct-12 23:05 
GeneralRe: My vote of 1 Pin
ManojKumar198-Oct-12 12:09
ManojKumar198-Oct-12 12:09 
GeneralMy vote of 2 Pin
eddy morrison22-May-12 2:08
eddy morrison22-May-12 2:08 

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

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