WP7 访问主页元素
我正在尝试制作一个简单的 Windows Phone 7 Silverlight 应用程序。其中包含一些 UI 元素的 MainPage.xaml
以及包含一些代码的单独 C# 类 MyClass.cs
。
我的问题是:MyClass
无法访问MainPage
中包含的任何内容(即它不知道UI 元素或C# 方法的存在)。
如果我尝试继承 MainPage
,应用程序会编译,但拒绝运行:
public class MyClass : MainPage
{
// No good
}
如果我尝试 此解决方案,然后我收到 InvalidCastException
错误:
public class MyClass
{
// Also no good
MainPage m = (MainPage)Application.Current.RootVisual;
}
我的问题是:如何从单独的类访问MainPage
?
在 MainPage.xaml.cs
中,我可以简单地使用 myElement.Property
等。但是,这在 MyClass
中是不可能的,但我'我不知道为什么。
我想我缺少一个简单的答案,但我真的不确定它是什么(... C# 新手在学会走路之前试图跑步!?)。
预先感谢您提供的任何建议。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
答案是,您不应该这样做,因为这种级别的耦合很可能会在未来的重用(尤其是测试)方面引起问题。
您可以考虑拥有一个单独的全局视图模型,其中包含您需要的信息(属性)并绑定到主视图的视图模型。
如果您需要类在视图上调用方法,那么您可以查看消息传递系统或类似系统。
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.