Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi
I am a beginner when it comes to MVVM. I am creating a WPF application using MVVM pattern. In the a MainWindow that have some contents and a Login View. I want open Login View over MainWindow view. User have to login first to access the content of MainWindow but the problem is I can access the View from View model.

How I can solve this problem? Please help
Posted
Comments
Rohit R Chavan 26-Nov-14 3:59am    
have a look

http://www.codeproject.com/Articles/554677/View-Control-from-a-ViewModel-with-ViewCommands

You should not open a another view from ViewModel because it is against the MVVM pattern as "Hari p balineni" already said. So, instead of Creating Login Window, You can convert it into the UserControl and place it into your main window like
C#
<v:logincontrol x:name="loginControl" height="270" width="560" xmlns:x="#unknown" xmlns:v="#unknown" />

and at code behind of the Login UserControl

C#
public partial class LoginControl : UserControl
   {
       private UIElement parent;

       private string Username;
       private string Password;


       public ThreatBaseInformationTemplateV2()
       {
           InitializeComponent();
           this.Visibility = System.Windows.Visibility.Hidden;
       }

       public void SetParent(UIElement parent)
       {
           this.parent = parent;
       }

       public void ShowHandlerDailog()
       {
           this.Visibility = System.Windows.Visibility.Visible;
           this.parent.IsEnabled = false;
       }

       public void HideHandlerDialog()
       {
           this.Visibility = System.Windows.Visibility.Hidden;
           this.parent.IsEnabled = true;
       }

       private void btnLogin_Click(object sender, RoutedEventArgs e)
       {
           Username = txtUsername.Text;
           Password = txtPassword.Text;
           this.parent.IsEnabled = true;
           this.Visibility = System.Windows.Visibility.Hidden;
       }

       private void btnCancel_Click(object sender, RoutedEventArgs e)
       {
           this.parent.IsEnabled = true;
           this.Visibility = System.Windows.Visibility.Hidden;
       }
   }

Now, In the constructor of the MainWindow you can set the parent of this control like

this.loginControl.SetParent(KBEditor);

and the you can show this on LoadEvent of MainWindow.

Hope it will help.
 
Share this answer
 
Comments
Rahul Kumar 26-Nov-14 5:32am    
Thanks
Openening View in Viewmodel is against MVVM
 
Share this answer
 
Comments
Rahul Kumar 26-Nov-14 4:54am    
Thanks for the reply
Is there any other option to do this?

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900