如何从任何其他非UI类引用Windows Phone主页上的控件?

时间:2013-05-20 10:41:30

标签: windows-phone-7 windows-phone

我以为我可以使用

从同一命名空间中的任何非ui类访问主页面上的控件
            var frame = Application.Current.RootVisual as PhoneApplicationFrame;
            var startPage = frame.Content as PhoneApplicationPage; 

但intellisense没有显示任何控制。

在谷歌上找不到任何奇怪的东西。

1 个答案:

答案 0 :(得分:4)

如果您想从其他课程访问您的控件,您可以:

  • 使用FindName方法检索它:

    var myButton = (Button)startPage.FindName("myButton");
    
  • 使用公共属性公开控件,并将页面强制转换为强类型而不是PhoneApplicationPage

    在ManPage.xaml.cs中:

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

    在你的其他班级:

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

请注意,从页面外部访问UI控件几乎总是一个坏主意。您可能想要重新考虑应用程序的体系结构而不是这样做(例如MVVM模式可以提供帮助)。