我正在尝试为我的 Windows Phone 应用程序实现 MVVM 模式。我的 View 位于一个项目中,App.xaml 位于另一个项目中。我将属性 IsTrial 添加到 App.xaml 但无法通过以下代码从 View 访问它:
if ((Application.Current as App).IsTrial)
因为我没有使用 App 类引用第一个项目,但我不能这样做,因为这会导致循环依赖。我能做些什么?如何访问App类?谢谢
最佳答案
在 Views 项目中创建一个界面:
public interface ISupportTrial
{
bool IsTrial { get; }
}
在App.xaml.cs中实现接口(interface):
public class App: Application, ISupportTrial
{
...
}
更改访问应用程序的代码:
var trialApp = Application.Current as ISupportTrial;
if (trialApp == null)
{
throw new NotSupportedException("Application.Current should implement ISupportTrial");
}
else if (trialApp.IsTrial)
{
...
}
else
{
...
}
注意:虽然这可能会起作用,但我认为访问 Application.Current 不是一个好的做法。您可能想阅读一些有关控制反转和依赖注入(inject)的文章。
关于c# - 如何获取App引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18189111/