Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
502 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...