How do I bind to MasterPage viewmodel inside a BindableLayout

陌路散爱 提交于 2021-02-05 11:30:07

问题


I am trying to bind my Command property to the Command in my MasterDetailPage view model. I tried defining the name property for the master page and setting that as the reference source, but it does not seem to bind to the viewmodel. For context, the List MenuItems is a property in the same Viewmodel and the Title binds just fine. I believe I am not setting the Source for the command correctly, but not sure how to fix it. Also, I am using Prism, so the viewmodel is mapped in app.xaml already.

<MasterDetailPage
x:Class="MasterDetailPrism.Views.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="http://prismlibrary.com"
prism:ViewModelLocator.AutowireViewModel="True"
x:Name="menuMasterPage">

<MasterDetailPage.Master>

    <ContentPage Title="Menu">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="225" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>


            <StackLayout Grid.Row="0" BackgroundColor="Aqua" />

            <StackLayout Grid.Row="1" BindableLayout.ItemsSource="{Binding MenuItems}">
                <BindableLayout.ItemTemplate>
                    <DataTemplate>
                        <StackLayout>
                            <Button
                                Command="{Binding NavigateAsync, Source={x:Reference menuMasterPage}}"
                                CommandParameter="{Binding NavPath}"
                                Text="{Binding Title}" />
                        </StackLayout>
                    </DataTemplate>
                </BindableLayout.ItemTemplate>
            </StackLayout>
        </Grid>

    </ContentPage>
</MasterDetailPage.Master>


回答1:


I was able to figure it out - I had to name the StackLayout, and then bind to the root of that as the source, not the contentpage or masterpage. In the code below, ItemsList.

        <StackLayout Grid.Row="1" BindableLayout.ItemsSource="{Binding MenuItems}" x:Name="ItemsList">
            <BindableLayout.ItemTemplate>
                <DataTemplate>
                    <StackLayout>
                        <Button
                            Command="{Binding BindingContext.NavigateAsync, Source={x:Reference ItemsList}}"
                            CommandParameter="{Binding NavPath}"
                            Text="{Binding Title}" />
                    </StackLayout>
                </DataTemplate>
            </BindableLayout.ItemTemplate>
        </StackLayout>


来源:https://stackoverflow.com/questions/59110501/how-do-i-bind-to-masterpage-viewmodel-inside-a-bindablelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!