c# - 如何获取App引用

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

我正在尝试为我的 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/

相关文章:

c# - 当我们使用 Nhibernate 3.2 的代码映射时,如何允许自动导入 ="true"?

c# - 如何使用 Mutex 创建锁?

c# - 如何使用 ReactiveCommand?

.net - 将ViewModel放在正确的位置

c# - WPF:MVVM - 如果命令为空则禁用按钮

c# - 不区分大小写的字典未按预期工作

c# - Powershell 导入自定义 C# CMDlet,无可用 "ExportedCommands"

c# - 带有 JSON.Net 的 Dictionary 中复杂类型的特定用途序列化

linq-to-sql - 为什么 LINQ to SQL 数据库没有保留在 WP7 模拟器中?

c# - 无法在 WP7 中使用 webClient.DownloadStringCompleted?