Superangel
Superangel

Reputation: 1349

WP7 Access MainPage Elements

I'm trying to make a simple Windows Phone 7 Silverlight app. There's the MainPage.xaml with some UI elements, and a separate C# class MyClass.cs with some code.

My problem is: MyClass can't access anything contained in MainPage (i.e. it doesn't know the UI elements or C# methods exist).

If I try to inherit MainPage, the app compiles, but refuses to run:

public class MyClass : MainPage
{
   // No good
}

If I try this solution, then I get an InvalidCastException error:

public class MyClass
{
  // Also no good
  MainPage m = (MainPage)Application.Current.RootVisual;
}

My question is: how can I access MainPage from a separate class?

In MainPage.xaml.cs, I can simply use myElement.Property etc. However, this isn't possible in MyClass, but I'm not sure why.

I guess there's a simple answer that I'm missing, but I'm really not sure what it is (... C# newbie trying to run before he can walk!?).

Thanks in advance for any advice you can offer.

Upvotes: 1

Views: 1243

Answers (1)

Matt Lacey
Matt Lacey

Reputation: 65566

The answer is that you shouldn't be doing this as this level of coupling is likley to cause issues in the future in terms of reuse and particularly testing.

You could look at having a separate global view model which has the information (properties) you need and is bound to the view model of the main view.

If you need your class to call methods on the view then you could look at a messaging system or similar.

Upvotes: 2

Related Questions