我正在尝试为我的Windows Phone应用程序实现MVVM模式。我在一个项目中有我的视图,在另一个项目中有App.xaml。我将属性IsTrial添加到App.xaml但我无法通过此代码从View中获取:
if ((Application.Current as App).IsTrial)
因为我没有用App类引用第一个项目,但我不能这样做,因为这会导致循环依赖。我能做什么?我如何访问App类?感谢
答案 0 :(得分: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不是一个好习惯。您可能想阅读一些关于控制和依赖注入反转的文章。