Binding UWP Page Loading/ Loaded to command with M

2019-01-27 07:35发布

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.

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>

In the ViewModel

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

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

Loaded="{Binding LoadedCommand}"

or

Loading="{Binding LoadingCommand}"

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

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.

How can I bind this Command properly?

标签: c# mvvm uwp Prism
1条回答
时光不老,我们不散
2楼-- · 2019-01-27 08:29

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>
查看更多
登录 后发表回答