user310291
user310291

Reputation: 38228

How to reference a control on windows phone main page from any other non UI class?

I thought I could access a control on main page from any non ui class in same namespace by using

            var frame = Application.Current.RootVisual as PhoneApplicationFrame;
            var startPage = frame.Content as PhoneApplicationPage; 

But intellisense doesn't show up any control.

Didn't find anything on Google that's weird.

Upvotes: 0

Views: 646

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39007

If you want to access your control from another class, you can either:

  • Use the FindName method to retrieve it:

    var myButton = (Button)startPage.FindName("myButton");
    
  • Expose the control with a public property, and cast the page to its strong type rather than PhoneApplicationPage:

    In ManPage.xaml.cs:

    public Button MyButton
    {
        get
        {
            return this.myButton;
        }
    }
    

    In your other class:

    var frame = (PhoneApplicationFrame)Application.Current.RootVisual;
    var startPage = (MainPage)frame.Content; 
    
    // Here, you can use startPage.MyButton
    

Note that accessing a UI control from outside of the page is almost always a bad idea. You may want to re-think your application's architecture rather than doing that (the MVVM pattern can help for instance).

Upvotes: 4

Related Questions