绑定UWP页面加载/通过MVVM加载到命令 [英] Binding UWP Page Loading/ Loaded to command with MVVM

查看:58
本文介绍了绑定UWP页面加载/通过MVVM加载到命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Preferrably written in PRISM (Prism.Core 6.2, Prism.Windows 6.02), but I also would like to know how to bind Command to Page Loading/ Loaded event in UWP with normal MVVM without Prism.

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

In WPF, it is achievable with:

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>

在ViewModel中

In the ViewModel

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

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

But in UWP, System.Windows.Interactivity does not exist. Simply binding with

Loaded="{Binding LoadedCommand}"

Loading="{Binding LoadingCommand}"

将得到编译错误对象引用未设置对象的实例".

will get compile error "Object reference not set an instance of an object".

我要这样做的原因是因为有一个异步方法需要在Page加载期间或之后完成(它不能在ViewModel构造函数内部).我可以轻松地使用后面的代码来完成此操作,但这不是MVVM.

The reason I wanted to do this is because there is an async method that needs to be done during or after Page is loaded (it cannot be inside ViewModel constructor). I could do it with code behind easily, but this is not MVVM.

如何正确绑定此命令?

推荐答案

行为也可在UWP中获得.只需添加 Microsoft.Xaml.Behaviors.Uwp.Managed 包装,就可以出发了.

Behaviors are also available in UWP. Simply add the Microsoft.Xaml.Behaviors.Uwp.Managed package and you're ready to go.

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>

这篇关于绑定UWP页面加载/通过MVVM加载到命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆