首页 > 解决方案 > 如何向 XAML 页面 BindingContext 提供具有带有参数的构造函数的 ViewModel

问题描述

将 ViewModel提供BindingContext到 XAML 页面具有 IntelliSense 的好处。但是,此语法仅在ViewModel具有空承包商时才有效,例如: MainPageViewModel()

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

如果 MainPageViewModel 没有空构造函数而只有参数构造函数,例如:MainPageViewModel(param1, param2),那么上面的 XAML 语法将抛出编译错误。我将如何在 XAML 中执行此操作?

标签: c#wpfxamarin.forms

解决方案


在查看WeeklyXamarin.Mobile Repo之后。我发现这可以通过以下方式很好地实现:

  • 创建PageBase如下:

公共类 PageBase : ContentPage { }

public class PageBase<TViewModel> : PageBase
{
    public TViewModel ViewModel { get; set; }

    public PageBase()
    {
        BindingContext = ViewModel = Container.Instance.ServiceProvider.GetRequiredService<TViewModel>();
    }
}

然后可以x:TypeArguments像这样传入 XAML 中的 ViewModel:

<views:PageBase
x:Class="WeeklyXamarin.Mobile.Views.AboutPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewmodels="clr-namespace:WeeklyXamarin.Core.ViewModels;assembly=WeeklyXamarin.Core"
xmlns:views="clr-namespace:WeeklyXamarin.Mobile.Views"
xmlns:vm="clr-namespace:WeeklyXamarin.Core.ViewModels;assembly=WeeklyXamarin.Core"
Title="{Binding Title}"
x:TypeArguments="viewmodels:AboutViewModel"
mc:Ignorable="d">

AboutViewModel在承包商中有一个参数,并且可以很好地与应用程序配合使用

 public AboutViewModel(INavigationService navigation, IDataStore dataStore) : base(navigation)

信用:Kym Phillpotts 先生在 WeeklyXamarin 回购中的代码


推荐阅读