gpt4 book ai didi

c# - 一个 ViewModel 和多个 View

转载 作者:太空狗 更新时间:2023-10-30 00:19:31 26 4
gpt4 key购买 nike

我有一些关于 Windows Phone 8 和 MVVM 模式的问题。

  1. 我想知道如何将来自许多显示页面的元素绑定(bind)到一个 ViewModel(只有一个 ViewModel,因为我想使用外观模式)。

  2. 我看到的每个教程都包含 ViewModel 和 Model 位于静态字段中的代码。我不确定这是否正确。有人能告诉我应该在 WP8 应用程序的哪个位置创建新模型和 ViewModel 才能正确执行吗? (我所说的“正确”还意味着我可以将来自多个页面的元素绑定(bind)到这个 ViewModel。)我正在考虑 App.xaml.cs 文件,但仍然不确定。

感谢您的帮助!

最佳答案

我最近一直在用类似的问题困扰自己。最后我用了App.xaml.cs创建 View 模型。

答案

是的,这是在 App.xaml.cs 中创建静态 View 模型的正确方法,因为 App类可以从应用程序中的任何页面访问,将它们声明为静态也是正确的,因为您将要访问它而不创建 App 的实例,并且正如 Tariq 在他的回答中所写:

ViewModel and Model are static fields so the values are not destroyed if they go out of scope. This further enables easy updating from multiple pages.

编辑:请注意,当您在页面之间浏览并返回时,绑定(bind)不会在您返回内存中的页面后自动恢复。

如何

我将其添加到 App.xaml.csRootFrame 的定义旁边:

private static MainViewModel viewModel; //not sure how your viewmodel class is named
public static MainViewModel ViewModel //and a property to access it from
{
get
{
if(viewModel == null) //which creates the viewModel just before
viewModel = new MainViewModel(); //it's first used
return viewModel;
}
}

当我想在我的页面中绑定(bind)一些东西时,jst 将其添加到页面的构造函数中(在 InitializeComponents(); 之后):

DataContext = App.ViewModel;

<罢工>

如果你想绑定(bind),你最好在 OnNavigatedTo() 中设置绑定(bind)(前提是构建它的资源成本不是太高 - 如果它需要花费更多的时间或资源,你应该考虑重新设计你的 ViewModel 以便它随着时间的推移加载)。

只需将此添加到您的页面:

    protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e); //not needed, base method is empty and does nothing
DataContext = null; //important part, whenever you navigate, refreshes the ViewModel - no deletion, just resetting of the DataContext, so the page won't get stuck
DataContext = App.ViewModel; //and finally the resetting
}

解释这段代码的作用以及我为什么要这样编辑我的代码:

  • 在制作我的应用程序时,我一直在关注应用程序内导航,例如后退浏览 - 当我按下硬件后退按钮并转到上一个站点时,即使我在页面中更改了它们,值也没有改变我回过头来。它们在模型中表现良好,但在“反向浏览”时未正确绑定(bind)。

当我试图解决它时,它最终出现了。

刷新绑定(bind)所需要做的就是:

  • 再次设置,由于回浏览时不调用页面的构造函数,唯一刷新页面的地方是OnNavigatedTo()事件。

  • 我测试了它并且它有效

(因此,当创建第一个页面并尝试绑定(bind)数据时,viewmodel 仅通过 get 请求自动创建:))

在 xaml 中,我可以通过以下方式进行绑定(bind):

<TextBlock text="{Binding SomePropertyNameFromViewModel}" />

<TextBlock text="{Binding SomeModelInViewModel.ItsProperty}" />

或者例如:

<ListBox IemSource="{Binding SomeCollectionInViewModel}">
...rest omitted for brevity...

等等...

最好的是什么?它有效并且相当容易。我将它用于带有多个命令的 ViewModel 以及大约 6 或 7 个包含用于绑定(bind)的属性和集合的模型,这些模型会随着用户浏览应用程序并指定要加载的内容而填充。

P.S.:据我所知,这是实现它的方式,即使是基本的 WP pivot 应用程序也是这样做的。

您可以检查自己是否创建了一个空的数据透视应用程序并查看 App.xaml.cs ,将会有一个像这样创建的 View 模型。并且可以从每个页面访问它。

关于c# - 一个 ViewModel 和多个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19415054/

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