UWP NavigationView通过MVVM导航

All*_*zod 3 c# navigation mvvm uwp

我在我的应用程序NavigationView中用作主控件,并且在页面加载位置具有框架。

<NavigationView x:Name="MyNavView" IsBackButtonVisible="Collapsed" SelectionChanged="{x:Bind ViewModel.OnSelectionChanged}" PaneDisplayMode="Top">
    <NavigationView.MenuItems>
        <NavigationViewItem Icon="Contact" Content="Contact" Tag="MasterDetailPage"/>
        <NavigationViewItem Icon="Favorite" Content="Favorites" Tag="FavoritesPage"/>
    </NavigationView.MenuItems>
    <Frame x:Name="RootFrame"/>
</NavigationView>
Run Code Online (Sandbox Code Playgroud)

有两个事件SelectionChangedItemInvoked,可用于实现对在RootFrame(我的框架的名称)中加载的页面的导航。但是我想使用Command制作MVVM。而且我什至没有为CommandView本身或NavigationViewItem找到Command道具。之后,我在ViewModel中处理了SelectionChanged事件,但在我看来,这与MVVM相矛盾。

那么,如何使用Command制作MVVM?如果没有这样的机会,请告诉我如何实现MVVM本身不处理事件。

Mar*_*man 5

实现此功能与WPF的实现非常相似,您需要首先通过NuGet安装Microsoft.Xaml.Behaviors.Uwp.Managed程序包。然后将行为添加到NavigationView中:

xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"

<NavigationView MenuItemsSource="{x:Bind ViewModel.MenuItems}">

    <i:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="ItemInvoked">
            <core:EventTriggerBehavior.Actions>
                <core:InvokeCommandAction Command="{x:Bind ViewModel.ItemInvokedCommand}" />
            </core:EventTriggerBehavior.Actions>
        </core:EventTriggerBehavior>
    </i:Interaction.Behaviors>
Run Code Online (Sandbox Code Playgroud)

我在x:Bind这里用于编译时错误检查,但是常规程序Binding当然也可以工作。无论哪种方式,都可以像在WPF中那样在视图模型中继续使用命令处理程序:

private ICommand _ItemInvokedCommand;
public ICommand ItemInvokedCommand => this._ItemInvokedCommand ?? (this._ItemInvokedCommand = new RelayCommand<NavigationViewItemInvokedEventArgs>(OnItemInvoked));


private void OnItemInvoked(NavigationViewItemInvokedEventArgs args)
{
    // could also use a converter on the command parameter if you don't like
    // the idea of passing in a NavigationViewItemInvokedEventArgs
    this.NavigationService.NavigateTo(args.InvokedItem);
Run Code Online (Sandbox Code Playgroud)