gpt4 book ai didi

c# - 使用 MVVM 模式设计需要 BackgroundAgent 的应用程序的最佳实践

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

虽然标题似乎过于宽泛,但实际上我还没有找到任何关于如何解决这个问题的提示。


编辑:虽然我正确地标记了问题,但我忘了写我正在使用 Caliburn.Micro,这意味着我必须同时拥有 ViewsViewModels 在同一个项目中,这迫使我为 Model 创建一个单独的库项目,作为 Background Agent 不能依赖应用的项目


在深入探讨这个问题之前,这里有一个情况的小例子:

- App Solution
\- Model (C# library)
\- Background agent
\- Real App
\- Views
\- ViewModels
\- Resources and other stuff

真实应用后台代理取决于模型

在我看来,这是让事情在我的场景中正常工作的最简单方法。

当我需要使用绑定(bind)时,问题就来了。在我以前的项目中,我曾经将 ModelViewModel 类合并为一个,这样我就可以将 XAML 绑定(bind)到 VIewModel 的属性没有任何问题。

但是现在,由于我不得不将我的模型保留在一个单独的项目中(后台代理不能依赖于真实应用),我不知道这应该如何工作。

为了让事情变得更复杂,我的模型使用异步模式来加载数据。

这引出了第一个问题:由于 Model 使用 async 模式加载数据,我如何通知 ViewModel数据准备好显示了吗?

为了使问题更清楚,这里有一个关于这个问题的简短片段:

namespace Models
{
public class Model
{
private string _neededProperty;
public string NeededProperty
{
get
{
return _neededProperty;
}
set
{
if (value == _neededProperty) return;
_neededProperty = value;
OnPropertyChanged();
}
}

public Model()
{
LoadData();
}

private async void LoadData()
{
NeededProperty = await StuffLoader();
}

private Task<string> StuffLoader()
{
return LoadStringAsync();
}
}
}

namespace ViewModels
{
public class ViewModel
{
public string NeededProperty
{
get
{
// Let's assume that we have a global instance of our model defined in the App.xaml.cs file
return App.Model.NeededProperty;
}
}
}
}

// Page.xaml
...
<TextBlock Text="{Binding NeededProperty, Source={StaticResource ViewModel}}"/>
...

Model 加载字符串后,我如何确定 TextBlock 加载正常?

当然,要使Background Agent 工作,也需要解决相同的问题,因为它依赖于Model 的相同加载方法。

所以,基本上,问题是:假设我的结构是正确的,并且这是组织项目的最佳方式,我如何“倾听”模型的属性来报告每个更改为 ViewModelBackground Agent

这对于显示某种加载屏幕也很有用,它必须显示在 Real App 部分,所以我需要知道 Model 实际上是什么时候完成其加载例程。

我希望这个问题很清楚,我现在有点困惑,因为这需要来自 Java 的大范式转变!

最佳答案

ViewModel 不应与 Views 在同一个项目中。这样您就可以根据需要在不同的应用程序中重复使用 Model 和 ViewModel(例如:桌面和手机应用程序)。因此,我会在 View 模型中使用您的后台代理(可能通过模型​​取决于您正在做什么)。这样,应用程序就不知道后台代理,并且您的应用程序使用 ViewModel 的方式与使用或不使用 ViewModel 的方式相同

IMO 这是最干净、最简单的方法。

关于c# - 使用 MVVM 模式设计需要 BackgroundAgent 的应用程序的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333709/

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