gpt4 book ai didi

C# MVVM - 访问 ViewModel 函数的模型

转载 作者:行者123 更新时间:2023-12-03 10:28:10 25 4
gpt4 key购买 nike

我正在为 Windows 通用应用程序在 MVVM 中实现 REST API 实现。

一切顺利,但我想解决一件事。

我在模型级别有​​一个 Post 和一个 Comment 类,它们有 Downvote 和 Upvote 功能。 API 调用在 ViewModel 中实现,包括告诉服务器进行 downvote-upvote 的调用。

我想要模型的 Downvote/Upvote 函数来触发 ViewModel 的适当调用。有可能还是我绕错了方向?

最佳答案

你被困在大多数从 MVVM 开始的程序员都被困住的地方。你只看 MVVM 并严格忽略其他一切。

你看到的是:Model , ViewModelView并且您尝试将所有业务逻辑放入其中之一。
但是 Model部分不仅仅是带有一点逻辑的 POCO 对象。服务也属于模式。这是您封装所有不属于某个模型的业务逻辑的地方。

您可以实现 PostService类和 CommentService类,它们都实现了 UpVote/DownVote 功能并从您的 ViewModel 调用这些服务。

public interface ICommentService
{
void UpVote(Post post, Comment comment);
void DownVote(Post post, Comment comment);
}

public class CommentRestService
{
IRestClient client;
public CommentRestService(IRestClient client)
{
this.client = client;
}

public void UpVote(Post post, Comment comment)
{
var postId = post.Id;
var commentId = comment.Id;

var request = ...; // create your request and send it

var response = request.GetResponse();

// successfully submitted
if(response.Status == 200)
{
comment.VoteStatus = VoteType.Up;
comment.Score += 1;
}
}

public void DownVote(Post post, Comment comment)
{
var postId = post.Id;
var commentId = comment.Id;

var request = ...; // create your request and send it

var response = request.GetResponse();

// successfully submitted
if(response.Status == 200)
{
comment.VoteStatus = VoteType.Down;
comment.Score -= 1;
}
}
}

在您的 ViewModel 中,您只需通过依赖注入(inject)传递服务或通过 ServiceLocator 获取它,然后使用它的方法,而不是调用 UpVote/ DownVote模型上。
// in ViewModel

// get via ServiceLocator or DI
ICommentService commentService = ...;
commentService.UpVote(this.Post, this.SelectedComment);

您还可以在模型上实现此方法,以将操作封装到 Comment 类中,即通过制作 ScoreVoteStatus “私有(private)套装;”
public class Comment 
{
public string Comment { get; set; }
public Post Post { get; private set; }
public VoteType VoteStatus { get; private set; }
public int Score { get; private set; }

public void UpVote(ICommentService commentService)
{
// for this you'd change your Up/Vote method to return only true/false and not
// change the state of your model. On more complex operation, return an CommentResult
// containing all necessary information to update the comment class
if(commentService.UpVote(this.Post, this))
{
// only update the model, if the service operation was successful
this.Score++;
this.VoteStatus = VoteType.Up;
}
}
}

并通过调用它
SelectedComment.UpVote(commentService);

后一种方法是首选,因为您可以更好地控制 Comment对象和 Comment的状态只能通过 Comment 进行修改它是方法类。这可以防止在代码中的其他地方意外更改此值并接收不一致的状态(即更改 VoteStatus 而不增加 Score 值)。

关于C# MVVM - 访问 ViewModel 函数的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27201122/

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