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.

asked Sep 25, 2015 at 9:13
\$\endgroup\$

1 Answer 1

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.

answered Sep 28, 2015 at 5:22
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.