1
\$\begingroup\$

Given these classes:

public partial class MainPage : UserControl
{
    public MainPage()
    {
       InitializeComponent();
       //...

    }
}
public partial class LoginForm : StackPanel
{
   private LoginRegistrationWindow parentWindow;
   private LoginInfo loginInfo = new LoginInfo();
   public LoginForm()
   {
       InitializeComponent();
       //...
   }

   private void LoginOperation_Completed(LoginOperation loginOperation)
   {

    if (loginOperation.LoginSuccess)
    {
            // Here I need to access MainPages's DataContext property and set it with my ViewModel
    }
   }
}

I want to set MainPage's DataContext property inside LoginFrom. So I created the static instance of the MainPage class in the class itself:

public partial class MainPage : UserControl
{
    public static MainPage Instance { get; private set; }
    public MainPage()
    {
        InitializeComponent();
        Instance = this;
    }
}

Now I can access to the MainPage's DataContext this way:

MainPage.Instance.DataContext = new NotificationItemViewModel();

Now I'd like to hear your ideas about this kind of passing data between classes in a Silverlight application. Do you have any idea?

PS: actually I answered my original question here on Stackoverflow. But I'd like to hear your ideas in terms of code review.

\$\endgroup\$
1
\$\begingroup\$

Based on what I understood from your question here are my 5ct.

The MainPage class is the parent class of the LoginClass.

  • Parents should talk to children by using methods.
  • Children should talk to parents by using events.

So you should raise an event from the LoginClass to be consumed by the MainPage instead of accessing a property of the MainPage.

In this way you can easily test the code of the LoginForm independently of the MainPage whereas in you current implementation a MainPage always needs to be created before the LoginOperation_Completed() method can be used.

In addition in its current state your implementation has side effects because each time you create a new MainPage the Instance property will be changed.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.