c# - 如何向 XAML 页面 BindingContext 提供具有带有参数的构造函数的 ViewModel
问题描述
将 ViewModel提供BindingContext
到 XAML 页面具有 IntelliSense 的好处。但是,此语法仅在ViewModel
具有空承包商时才有效,例如: MainPageViewModel()
<ContentPage.BindingContext>
<viewModels:MainPageViewModel />
</ContentPage.BindingContext>
如果 MainPageViewModel 没有空构造函数而只有参数构造函数,例如:MainPageViewModel(param1, param2),那么上面的 XAML 语法将抛出编译错误。我将如何在 XAML 中执行此操作?
解决方案
在查看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 回购中的代码
推荐阅读
- android - 如何将此 url 图像加载到图像视图中我尝试了 Glide 和图像加载器但没有工作
- ios - Swift pushViewController 导致应用程序崩溃
- aws-codepipeline - CodeBuild 成功,但 CodeDeploy 失败
- tcp - 为什么 tcp 接收应该循环工作?
- visual-studio-code - 除非使用相对路径,否则 VSCode 不会转到定义
- django - 将 Django 模型中的 default_value 应用于数据库
- android - 视图元素在小屏幕中无法正确显示
- python - 处理 pygame 中的一长串数字
- mailkit - 是否存在基于 MailKit 库构建的已知邮件客户端应用程序?
- pandas - 熊猫日期时间与星期几