【问题标题】:MasterDetail navigation using prism使用棱镜的 MasterDetail 导航
【发布时间】:2017-04-22 16:27:58
【问题描述】:

我最近开始使用 Prism 构建 Xamarin Forms 应用程序。

我无法使用 MasterDetail Navigation 进行导航。我用来导航的按钮似乎无法正确绑定。单击按钮时,我永远无法使用断点到达已执行的命令。 除了命令绑定之外的所有内容似乎都正确地进行了绑定,所以我真的不知道发生了什么。

我已经查看了 Prism 团队提供的 GitHub 示例(HamburgerMenu 项目)。我确信使用与示例完全相同的配置,但无法使其适用于我的项目。

下面是当前使用的代码:

MainPage.xaml

<MasterDetailPage 
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="MonkeyVault.Views.MainPage">
    <MasterDetailPage.Master>
        <NavigationPage Title="Required Foo" Icon="ic_menu.png">
            <x:Arguments>
                <ContentPage Title="Menu">
                    <StackLayout Padding="40">
                        <Label Text="{Binding UserName, StringFormat='Hello, {0}'}"/>
                        <Button Text="Sites" Command="{Binding NavigateCommand}" CommandParameter="Navigation/Sites" />
                    </StackLayout>
                </ContentPage>
            </x:Arguments>
        </NavigationPage>
    </MasterDetailPage.Master>
</MasterDetailPage>

MainPageViewModel.cs

public class MainPageViewModel : BaseViewModel
        {
            #region Fields

            private string _userName;

            #endregion

            #region Properties

            public string UserName
            {
                get => _userName;
                set => SetProperty(ref _userName, value);
            }

            public DelegateCommand<string> NavigateCommand;

            public DelegateCommand NCommand;

            #endregion

            public MainPageViewModel(INavigationService navigationService)
                : base(navigationService)
            {
                Title = "Main Page";

                NavigateCommand = new DelegateCommand<string>(OnNavigateCommandExecuted);
            }

            private async void OnNavigateCommandExecuted(string path)
            {
                await _navigationService.NavigateAsync(path);
            }
        }

如果有人已经遇到过这个问题或有任何想法,我会很感激。

【问题讨论】:

  • 不是我对Prism太熟悉,而是BIndingContext和MasterDetailPage是怎么做的。在 MasterDetailPage 中,master 和 detail 部分都应将其 BIndingContext 设置为适当的 ViewModel。
  • @AdamPedley 这个视图通过命名约定自动连接到视图模型,允许数据绑定到视图模型。它有效,“用户名”属性上的绑定按预期工作,只有命令绑定没有被触发,我不知道为什么。

标签: xamarin.forms


【解决方案1】:

您需要将您的 DelegateCommand 创建为属性。

public DelegateCommand<string> NavigateCommand { get; set; }

诚然,我只是在这里猜测,但我之前在绑定到 Fields 时遇到过问题,需要将其更改为属性以进行绑定。

【讨论】:

  • 非常感谢!我真的不明白为什么,但它工作得很好。你让我开心!
  • 虽然我还没有深入研究 Xamarin 中的 BindingEngine,但由于必须使用反射来获取要绑定的属性,所以它将使用 GetRuntimeProperty 等方法。这些只会获取属性,因为你必须使用不同的方法来获取字段。
  • 感谢您提供详细的解答。像往常一样,你似乎消息灵通。顺便说一句,我最近有幸在xamarinhelp.com 中阅读了您关于 Xamarin 表单的文章。它写得很好,包含了很多实用的好建议。我期待着阅读你的下一篇文章。请继续做这么好的工作:)
猜你喜欢
  • 1970-01-01
  • 2012-03-16
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
相关资源
最近更新 更多