简体   繁体   中英

Windows Phone 7 - Access MainPage UI control from Class

I need to access control of MainPage.xaml.cs from another class. How can I access it?

The question is why? There are a couple of approaches, depending on your architecture:

First thing you can do is to make your MainPage singleton. It makes sense because you only have one Main Page in reality too, but I don't like singletons, and it makes your components coupled and your design becomes hard to unit test.

Alternatively, you can pass an interface of your MainPage into your class. If you only pass the interface, you then have the chance to do unit testing without too much trouble. Something like this:

public interface IMainView
{
   void MethodOnMainPage();
}

public class MainPage : IMainView
{
}

public class MyClass 
{
   private IMainView _view;

   public MyClass(IMainView view)
   {
      _view = view;
   }

   private void SomeEventHappened() 
   {
      _view.MethodOnMainPage();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM