使用 MVVM 绑定 UWP 页面加载/加载到命令

Binding UWP Page Loading/ Loaded to command with MVVM

最好用 PRISM 编写(Prism.Core 6.2,Prism.Windows 6.02),但我也想知道如何在没有 Prism 的情况下使用普通 MVVM 将命令绑定到 UWP 中的页面加载/加载事件。

在 WPF 中,可以通过以下方式实现:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction Command="{Binding LoadedCommand}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

在视图模型中

public ICommand LoadedCommand { get; private set; }
public TheViewModelConstructor()
{
     LoadedCommand = new DelegateCommand(Load);
}
private async void Load()
{
    // Do stuff
}

但在 UWP 中,System.Windows.Interactivity 不存在。只需与

绑定
Loaded="{Binding LoadedCommand}"

Loading="{Binding LoadingCommand}"

会出现编译错误"Object reference not set an instance of an object"。

我想这样做的原因是因为有一个异步方法需要在页面加载期间或之后完成(它不能在 ViewModel 构造函数中)。我可以轻松地使用代码隐藏,但这不是 MVVM。

如何正确绑定此命令?

UWP 中也提供行为。只需添加 Microsoft.Xaml.Behaviors.Uwp.Managed 包,您就可以开始了。

Microsoft.Xaml.Behaviors.Uwp.Managed v1.x

<interactivity:Interaction.Behaviors>
    <core:EventTriggerBehavior EventName="Loaded">
        <core:InvokeCommandAction Command="{Binding ViewLoadedCommand}" />
    </core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>

Microsoft.Xaml.Behaviors.Uwp.Managed v2.x

<interactivity:Interaction.Behaviors>
    <core:EventTriggerBehavior EventName="Loaded">
        <core:EventTriggerBehavior.Actions>
            <core:InvokeCommandAction Command="{Binding ViewLoadedCommand}" />
        </core:EventTriggerBehavior.Actions>
    </core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>