【发布时间】:2020-10-26 06:33:43
【问题描述】:
我正在为我的宠物项目使用 MVVM 开发一个关于视频游戏的 Xamarin 表单应用程序。我是 Xamarin 表单的新手,我需要您的建议。
我有几个 ViewModel 中的代码相同。我决定创建一个基础 ViewModel 并从中继承其他的。
我有带有 PropertyChanged 事件的 ViewModelBase:
public class ViewModelBase : INotifyPropertyChanged
{
private string _title;
public string Title
{
get => _title;
set => Set(ref _title, value);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void Set<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
我还有一个继承其他人的基本 GamesViewModel,有很多代码,这就是为什么我只显示我正确继承了所有内容:
public class GamesViewModel : ViewModelBase
以下是派生的 ViewModel:
public class NewGamesViewModel : GamesViewModel
和
public class SearchViewModel : GamesViewModel
问题是我在基本 GamesViewModel 中有 SearchGame 属性:
private string _searchGame;
public string SearchGame
{
get => _searchGame;
set => Set(ref _searchGame, value);
}
程序运行时,我将值放在 SearchGame 属性中,在 GamesViewModel 中我可以看到分配的值,但在派生的 ViewModels 中值为 null:
例如,在继承自 GamesViewModel 的 SearchViewModel 中进行调试时,我检查了该值,它为空。
var test = SearchGame; - value is null here
我没有在项目中创建 GamesViewModel 的任何对象。
在 BindingContext 的页面代码隐藏文件中,我这样做:
public partial class SearchGamePage : ContentPage
{
public SearchGamePage()
{
InitializeComponent();
BindingContext = new SearchViewModel();
}
}
我试图尽可能多地解释。也许在 Xamarin 表单中,使用 ViewModels 的继承工作并不明显。
提前感谢您的帮助!
祝你有美好的一天!
【问题讨论】:
-
你有没有在setter上下断点,看看有没有其他代码设置成
null? -
@mjwills 我编辑了代码,我使用 var test = SearchGame;是的,我在设置器上放了一个断点,我说在基本 GamesViewModel 中分配的值没有问题,但在派生的视图模型中,值为 null :(
-
我们需要minimal reproducible example。我会说你正在写入的对象和正在读取的对象有 90% 的可能性是不同的对象。
-
@mjwills 是的,我同意它们是不同的对象,但我没有创建 GamesViewModel 的任何对象。也许我错过了什么
-
分享minimal reproducible example,我们来看看。还要在
SearchViewModel的构造函数中添加一个断点,这样你就可以看到它们什么时候被构造了。
标签: c# xamarin mvvm xamarin.forms viewmodel