2017-07-09 88 views
0

使用Xamarin网页代码中有景结合形态& PCL棱镜VM背后

我看到了很多的例子,段关于使用此块

xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms" 
     prism:ViewModelLocator.AutowireViewModel="True" 
在Page.Xaml

与景观结合VM

如果我想在后面的页面代码(Page.cs)中绑定视图模型该怎么办。

回答

0

您可以新建viewmodel并将其设置为BindingContext。

public Page() 
{ 
    InitializeComponent(); 
    this.BindingContext = new MyViewModel(); 
} 

==== ==== EDITED

如果您的视图模型是需要依赖注入参数,要正确地解决它。

App.xaml.cs

protected override void OnInitialized() 
{ 
    ... 
    Microsoft.Practices.Unity.UnityContainerExtensions.RegisterType<IMyViewModel, MyViewModel); 
    ... 
} 

Page.xaml.cs

public Page() 
{ 
    InitializeComponent(); 
    var viewModel = Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IMyViewModel>(((App)Application.Current).Container); 
    this.BindingContext = viewModel; 
} 
+0

因此,如果视图模型参数为 PageViewModel(INavigationService navigationService,IPageDialogService pageDialogService) –

+0

在这种情况下,您需要使用依赖注入来解析ViewModel。你可以让你的App类静态访问。然后调用App.Container.Resolve([viewmodel type])。但在此之前,您需要通过调用Container.RegisterType([viewmodel type],viewmodel class) – lowleetak

+0

将视图模型注册到Container中,尽管我的Dryioc.Icontainer类型的容器仍然可以使用它。 –

1

你必须通过对类两个参数实例化,因为你已经需要构造双参数该案。尝试下面的代码。

public Page() 
{ 
    InitializeComponent(); 
    this.BindingContext = new PageViewModel(Navigation,PageDialogService); 
} 
0

在我的情况

我从page.xaml

 xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms" 
    prism:ViewModelLocator.AutowireViewModel="True" 

和后面的码内移除(page.cs)

我增加

public Page() 
    { 
      InitializeComponent(); 
      this.BindingContext = new pageViewModel(null,null); 
    } 

它为我工作

+0

但您的NavigationService和PageDialogServer将在视图模型为空 – lowleetak

+0

为空,我同意你在某些页面_navigationservice有一个值,而在其他的一些它是空的,但仍然适用于这两种情况下,我希望你尝试和解释我。 –

2

你可以从代码访问视图模式的背后,是通过简单的类型转换绑定上下文

var pageViewModel = (PageViewModel)this.BindingContext; 

这对我的作品。