Prism with Xamarin.Forms-如何自动连接另一个ContentView中的ContentView
当ContentView直接包含在页面中时,我们使用XAML成功地将ContentView连接到它们的ViewModels,如:Prism with Xamarin.Forms-如何自动连接另一个ContentView中的ContentView,xamarin.forms,prism,Xamarin.forms,Prism,当ContentView直接包含在页面中时,我们使用XAML成功地将ContentView连接到它们的ViewModels,如: <local:AwesomeView mvvm:ViewModelLocator.AutowirePartialView=”{x:Reference self}” /> 其中self是父页面 但是,我们有包含ContentView的ContentView,并且在嵌套视图中使用上述AutoWirePartialView不起作用。ContentView没
<local:AwesomeView mvvm:ViewModelLocator.AutowirePartialView=”{x:Reference self}” />
其中self是父页面
但是,我们有包含ContentView的ContentView,并且在嵌套视图中使用上述AutoWirePartialView不起作用。ContentView没有连接到它们的ViewModels
查看Prism代码:
Prism-7.1.0.431为了保持整洁,我的观点是使用默认的Prism方法,仅将viewmodel绑定到相应的页面,而不绑定到任何子视图 对页面内部组件的任何绑定都应该通过页面的viewmodel上的属性进行,这样无论内容视图在显示层次结构中的深度如何,都可以实现绑定 例如: 页面的视图模型
public class PageAViewModel : ViewModelBase
{
public ContentViewAViewModel ContentViewViewModel
{
get { return _contentViewViewModel; }
set { SetProperty(ref _contentViewViewModel, value); }
}
}
您页面的视图
<?xml version="1.0" encoding="UTF-8"?>
<views:BasePage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:components="clr-YourProject.Components"
xmlns:views="clr-YourProject.Views"
x:Class="YourProject.Views.PageA">
<Grid RowSpacing="0">
<Grid RowSpacing="0">
<components:ContentViewA BindingContext="{Binding ContentViewViewModel}"/>
</Grid>
</Grid>
</views:BasePage>
局部视图确实已经过时。它过时的原因是,我们将使用棱镜8。在我们实现Prism.Forms的区域之前,部分视图总是作为一种快速和临时的解决方案来帮助弥补这一差距。区域功能更强大,可以让您执行更多类似嵌套和惰性加载视图的操作 实际上,嵌套区域的概念包括: ComponentViewA有自己的ViewModel 然后是ComponentViewB,它有自己的ViewModel,并将ComponentViewA作为子级 ComponentViewA本身就是AwesomePage的一个子公司 听起来这是您希望支持的一般概念。简单的回答是,在Prism 7中,没有好的方法可以做到这一点。当然也有一些黑客,比如你可以将页面作为参数传递,然后在代码中设置属性,比如:
公共类组件视图B:ContentView
{
公共静态只读BindableProperty ParentPageProperty=
创建(nameof(ParentPage)、typeof(Page)、typeof(ComponentViewB)、null、propertyChanged:OnParentPageChanged);
ParentPageChanged上的私有静态无效(BindableObject bindable、object oldValue、object newValue)
{
//这样可以防止操作被执行多次。
if(oldValue为null&&newValue!=null&&bindable为ComponentViewB视图)
{
//这假设您已经设置了属性x:Name=“componentViewA”
//用于XAML中的组件视图A
ViewModelLocator.SetAutowirePartialView(view.componentViewA,(view.ParentPage);
}
}
公共页父页
{
get=>(页面)GetValue(ParentPageProperty);
set=>SetValue(ParentPageProperty,value);
}
}
老实说,如果我今天必须做一些事情,我建议你这样做。一旦我们合并了我上面提到的PR,我建议你更新预览并迁移到使用区域。谢谢-我认为这是目前实现我想要的最简单的方法。在我们等待Prism 8.Gla时,它解决了“问题”我相信Dan对Prism的更新将为您提供一个更优雅的解决方案。谢谢-这是一个有趣的解决方案。我认为xerx上面的解决方案有点紧-对于您的解决方案,我们必须向每个ContentView添加父视图的知识。