不能更改视图模型名称,Xamarin UWP中没有MVVM视图模型的无参数构造函数



我目前正在制作一个使用MVVM作为其接口的Xamarin UWP应用程序。我的目标是10.0.19041.0的平台版本,最低为10.0.17763.0。目标框架是netstandard 2.0。我用的是Windows 10。

我在尝试更改视图模型的名称时遇到错误。当所讨论的视图模型具有其默认名称时,它可以完美地工作,但是当我更改名称时,由于无参数构造函数错误而崩溃。

这是不会崩溃的工作设置。我有一个名为DeviceListViewModel的视图模型类。下面是它的代码,包括带参数的构造函数:

public class DeviceListViewModel : BaseViewModel {
private readonly IBluetoothLE _bluetoothLe;
private readonly IUserDialogs _userDialogs;
private readonly ISettings _settings;
...
public DeviceListViewModel(IBluetoothLE bluetoothLe, IAdapter adapter, IUserDialogs userDialogs, ISettings settings, IPermissions permissions) : base(adapter) {
_bluetoothLe = bluetoothLe;
_userDialogs = userDialogs;
_settings = settings;
_bluetoothLe.StateChanged += OnStateChanged;
Adapter.DeviceDiscovered += OnDeviceDiscovered;
Adapter.ScanTimeoutElapsed += Adapter_ScanTimeoutElapsed;
Adapter.DeviceDisconnected += OnDeviceDisconnected;
Adapter.DeviceConnectionLost += OnDeviceConnectionLost;
BleMvxApplication._reader1.DisconnectAsync();
}
...
}

变量'Adapter'作为一个受保护的变量从BaseViewModel类继承,在BaseViewModel类中像这样初始化:

protected readonly IAdapter Adapter;

在上面所示的初始化之外的整个代码库中,只有一个使用DeviceListViewModel的位置。它在另一个文件中的ShowViewModel函数调用中被调用:

void OnConnectButtonClicked() {
...
ShowViewModel<DeviceListViewModel>(new MvxBundle());
...
}

当我尝试更改名称DeviceListViewModel时发生错误。在整个代码库中出现类名的三个地方,如果对它做了任何更改,就会得到无参数构造函数错误。

我已经尝试制作了一个,但是有一些问题。类需要参数才能正常工作,试图在没有参数的情况下创建一个类是错误的。下面是一些简单的例子:

public DeviceListViewModel() {} // fails since it does not inherit from BaseViewModelClass
public DeviceListViewModel() : base(adapter) {} // adapter does not exist in current context
public DeviceListViewModel() : base(Adapter) {} // An object reference is required for the non-static field, method, or property 'BaseViewModel.Adapter'

不考虑这些创建无参数构造函数的尝试,我需要像_bluetoothLe和_userDialogs这样初始化变量,因为它们在代码的其他部分被调用。

所以,重申一下,问题是更改类名会导致它失败。将'DeviceListViewModel'三次更改为'DeviceListViewModel1'将导致代码失败并发生无参数构造函数错误。我试图改变名字,因为我想让这个类的其他版本有不同的名字,但即使保持其他一切相同,只是改变名字会阻止类的功能。

欢迎任何建议!

我已经找到了解决方案,感谢@ToolmakerSteve的评论。

在与我的DeviceListViewModel关联的XAML中,有依赖于名称"DeviceList"的变量/XAML/XAML .cs文件。由于我将视图模型更改为DeviceListViewModel,因此它打破了mvvmcross和视图/视图模型连接使用的命名约定。

它现在通过将我的视图模型重命名为DeviceList1ViewModel并将所有的DeviceList变量重命名为DeviceList1来工作。

总之,即使我改变了我的视图模型'DeviceListViewModel'的每个实例,也有其他与'DeviceList'相关的代码函数,当它被重命名时,使我的viewmodel崩溃。如果您有类似的问题,请检查相关区域。

最新更新