【发布时间】:2021-04-19 04:07:02
【问题描述】:
ViewModels应该继承其他ViewModels吗?
我有一个MerchandiserViewModel,其中包含Merchandiser 模型的基本属性和数据库函数。
MerchandiserViewModel 有一个 SelectedMerchandiser 属性,该属性在 ListView 中保存从 ItemSelected 中选择的 Merchandiser
MerchandiserViewModel.cs
public MerchandiserViewModel : INotifyPropertyChanged
{
// Property to hold the selected Merchandiser
// Generally I would make this static but then I can't bind the property
public Merchandiser SelectedMerchandiser {get; set;}
// Other logic...
}
MerchandiserViewModel 在App.xaml 中被实例化为Static Resource,因此我只有一个视图模型实例。
App.xaml
<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MobileApp.App"
xmlns:ViewModels="clr-namespace:MobileApp.ViewModels">
<Application.Resources>
<ViewModels:MerchandiserViewModel x:Key="MerchandiserViewModel" />
<ViewModels:MerchandiserProfileViewModel x:Key="MerchandiserProfileViewModel" />
</Application.Resources>
</Application>
对于与跟单员相关的每个View,例如MerchandiserProfile、EditProfile 等。我创建了一个新的ViewModel 并继承了MerchandiserViewModel
MerchandiserProfileViewModel.cs 继承 MerchandiserViewModel
public class MerchandiserProfileViewModel : MerchandiserViewModel
{
// Logic Specific to the Merchandiser Profile View
}
问题是...当我创建一个新的[Page]ViewModel 并继承“MerchandiserViewModel”时,我收到以下错误消息。
我认为这可能是因为创建了 MerchandiserViewModel 的新实例,所以我没有引用初始的 SelectedMerchandiser 属性。
这让我觉得继承 ViewModel 不是个好主意?
这种情况通常如何处理?我是否应该将每个页面/视图的所有逻辑都塞到MerchandiserViewModel 中?我希望我的代码尽可能干净且独立,因此尽可能避免这种情况。
三思而后行
我可以在 C# 的静态资源中访问MerchandiserViewModel 的属性吗?这样我就可以将所需的属性传递给新的 ViewModel 而无需继承 MerchandiserViewModel ... 想听听对此的想法吗?
【问题讨论】:
-
我试过
MerchandiserViewModel merchandiserVM = (MerchandiserViewModel)Application.Current.Resources["MerchandiserViewModel"];,但我似乎无法以这种方式访问属性。 -
对stackoverflow.com/questions/67156588/… 上发布的有关访问静态资源属性的问题的回复。你没有,至少在 MVVM 中没有。 MVVM 将视图及其数据(视图模型)解耦。您要实现的目标违反了 MVVM 原则。这似乎是一个 XY 问题——MindSwipe
-
XY问题链接xyproblem.info
标签: c# xamarin xamarin.forms mvvm viewmodel