Jun*_*Jon 1 xaml xamarin.ios xamarin.android xamarin xamarin.forms
我有一个带有两个ContentViews的ContentPage,并且我想将它们各自的绑定上下文设置为各自的各自的ViewModel(这是我首选的合并形式,而不是一个庞大的ViewModel)
主页
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="MVVMFramework.VVMs.Main.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MVVMFramework"
xmlns:nav="clr-namespace:MVVMFramework.Navigation.NavigationHeader"
xmlns:vm="clr-namespace:MVVMFramework.VVMs.Main">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="200" />
</Grid.RowDefinitions>
//ContentView For Header
<ContentView Grid.Row="0"
HorizontalOptions="Start"
VerticalOptions="Start">
Content="{Binding NavHeader}"
<!--<ContentView.BindingContext>
<nav:NavigationHeaderViewModel />
</ContentView.BindingContext>-->
</ContentView>
//ContentView For Body of the app
<ContentView Grid.Row="1"
Content="{Binding DisplayedView}"
HorizontalOptions="Center"
VerticalOptions="Center">
<!--<ContentView.BindingContext>
<vm:MainPageViewModel />
</ContentView.BindingContext>-->
</ContentView>
</Grid>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)
当我取消注释这两个bindingcontext属性时,应用程序会编译,并开始运行,然后在加载MainPage时崩溃。
我执行不正确吗?还有另一种方法吗?
您可以使用其BindingContext属性为每个视图的绑定指定源,如下所示:
BindingContext="{Binding Source = {Your Binding Source}}"
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="MVVMFramework.VVMs.Main.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MVVMFramework"
xmlns:nav="clr-namespace:MVVMFramework.Navigation.NavigationHeader"
xmlns:vm="clr-namespace:MVVMFramework.VVMs.Main">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="200" />
</Grid.RowDefinitions>
<ContentView
Grid.Row="0"
Content="{Binding NavHeader}"
HorizontalOptions="Start"
VerticalOptions="Start"
BindingContext="{Binding Source = {nav:NavigationHeaderViewModel}}"/>
<ContentView
Grid.Row="1"
Content="{Binding DisplayedView}"
HorizontalOptions="Center"
VerticalOptions="Center"
BindingContext="{Binding Source = {vm:MainPageViewModel}}"/>
</Grid>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)
这是一个示例应用程序,显示了如何从同一ContentPage引用多个视图模型:https : //github.com/brminnick/MultipleViewModelSample/
| 归档时间: |
|
| 查看次数: |
2413 次 |
| 最近记录: |