【问题标题】:xamarin forms mvvm Missing default constructor forxamarin 形成 mvvm 缺少默认构造函数
【发布时间】:2021-05-27 22:36:48
【问题描述】:

我已经创建了 MessageCenterService 接口

public interface IDialogService
{
    Task Toasting(string title);
}

public class DialogService : IDialogService
{
    public async Task Toasting(string title)
    {
        using (var Dialog = UserDialogs.Instance.Toast(title, null))    
        {
            await Task.Delay(1000);
        }
    }
}   

现在我正在尝试依赖注入但是:

public class LoginViewModel : BaseViewModel
{
    private IDialogService _dialogService;

    public ICommand LoginCommand { get; set; }

    public LoginViewModel(IDialogService dialogService)
    {
        _dialogService = dialogService;
        LoginCommand = new Command(Login);  
    }
}   

错误 => 缺少“..LoginViewModel”的默认构造函数

LoginPage.xaml

  <ContentPage.BindingContext>
        <viewModels:LoginViewModel/>
  </ContentPage.BindingContext>

但如果我说:

public LoginViewModel(){}

public LoginViewModel(IDialogService dialogService) //:Base() :this
{
    _dialogService = dialogService;
    ...
}

错误消失,但 IDialogService 永远不会实例化 _dialogService 始终为空

LoginPage.xaml.cs 更改也不起作用..

public LoginPage()
{
    InitializeComponent();
}

public LoginPage(IDialogService dialogService): base()
{
    InitializeComponent();
}

我错过了什么?提前致谢

https://forums.xamarin.com/discussion/48009/pop-display-alert-message-from-viewmodel Missing Default Constructor error in Xamarin Forms Xamarin Forms -> System.MissingMethodException: Default constructor not found for [Interface] Missing Default Constructor error in Xamarin Forms

【问题讨论】:

    标签: c# xamarin xamarin.forms mvvmcross


    【解决方案1】:

    尝试使用 DependencyService 或 TinyIOC 等第 3 方库。 这是我使用 DependencyService 的示例代码。 您可以使用 DependencyService.Register() 注册您的服务,然后使用 DependencyService.Get();

    简单地调用它

    App.xaml.cs

    public App()
    {
       ...
       DependencyService.Register<DialogService>();
       ...
    }
    
    

    LoginPage.xaml.cs

    LoginPage()
    {
       InitializeComponent();
       BindingContext = new LoginViewModel();
    }
    

    LoginViewModel.cs

    private IDialogService _dialogService;
    
    public LoginViewModel()
    {
       ...
       _dialogService = DependencyService.Get<DialogService>();;
       ...
    }
    

    【讨论】:

      【解决方案2】:

      试试private readonly IDialogService _dialogService;

      【讨论】:

      • _dialogService continue null
      • “试试这个”并不是一个好的答案。你应该解释如何为什么这可以解决他们的问题。我推荐阅读,“How do I write a good answer?"。这可以帮助未来的用户学习并最终将这些知识应用到他们自己的代码中。当代码被解释时,你也可能会得到用户的积极反馈/赞成。
      猜你喜欢
      • 2020-07-05
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2020-09-29
      • 1970-01-01
      • 2019-07-21
      相关资源
      最近更新 更多