gpt4 book ai didi

xaml - 多个 BindingContext 在同一个 ContentPage 上,两个不同的 View ?

转载 作者:行者123 更新时间:2023-12-04 14:33:01 24 4
gpt4 key购买 nike

我有一个带有两个 ContentViews 的 ContentPage,我想将它们每个的绑定(bind)上下文设置为它们各自的 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>

当我取消注释两个 bindingcontext 属性时,应用程序将编译并开始运行,然后在加载 MainPage 时崩溃。

我是不是没有正确实现?,还有其他方法可以做到吗?

最佳答案

回答
您可以使用其 BindingContext 为每个 View 的绑定(bind)指定源。属性如下:BindingContext="{Binding Source = {Your Binding Source}}"示例应用程序
这是一个示例应用程序,展示了如何从同一 ContentPage 引用多个 View 模型:https://github.com/brminnick/MultipleViewModelSample/
代码

<?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>

关于xaml - 多个 BindingContext 在同一个 ContentPage 上,两个不同的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50307356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com