【问题标题】:How to get reference to App如何获取对 App 的引用
【发布时间】:2013-08-13 21:21:14
【问题描述】:

我正在尝试为我的 Windows Phone 应用程序实现 MVVM 模式。我在一个项目中有我的观点,在另一个项目中有 App.xaml。我将属性 IsTrial 添加到 App.xaml 但我无法通过以下代码从 View 中访问它:

if ((Application.Current as App).IsTrial)

因为我没有使用 App 类引用第一个项目,但我不能这样做,因为这会导致循环依赖。我能做些什么?如何访问 App 类?谢谢

【问题讨论】:

  • 在实例化它时不能将该信息传递到视图模型中吗?您的视图实际上应该只从视图模型中提取数据。
  • 我通常在具有这些属性的共享项目中创建一个静态 ApplicationInfo 类。这样就可以轻松地从与当前应用程序相关的任何项目中访问全局信息。

标签: c# windows-phone-7 mvvm windows-phone-8 mvvm-light


【解决方案1】:

在您的 Views 项目中创建一个界面:

public interface ISupportTrial
{
   bool IsTrial { get; }
}

在 App.xaml.cs 中实现接口:

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 不是一个好习惯。您可能想阅读一些关于控制反转和依赖注入的文章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2013-11-14
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多