gpt4 book ai didi

c# - 如何获取对应用程序的引用

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:38 25 4
gpt4 key购买 nike

我正在尝试为我的 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# - 如何获取对应用程序的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18189111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com