Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

c# - Binding UWP Page Loading/ Loaded to command with MVVM

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...