2

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

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

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

4

1 回答 1

2

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

于 2013-08-12T14:44:15.383 回答