OnInitialize and OnActivate are not called on child View Models
Asked Answered
R

3

12

I expected that child View Models inheriting from Screen would participate in the Parent Screen's life-cycle. However, it appears this is not the case. For example:

public class ParentViewModel : Screen
{
    public ChildViewModel Child { get; set; }

    public ParentViewModel(ChildViewModel childViewModel)
    {
        this.Child = childViewModel;
    }

    public override void OnInitialize() { // called - as expected }

    public override void OnActivate() { // called - as expected }

    public override void OnDeactivate() { // called - as expected }
}

public class ChildViewModel : Screen
{
    public override void OnInitialize() { // not called - why? }

    public override void OnActivate() { // not called - why? }

    public override void OnDeactivate() { // not called - why? }
}

Is it possible to have a child Screen participate in the parent Screen's life-cycle?

Rees answered 25/10, 2011 at 5:57 Comment(0)
R
22

It seems this behaviour is not by default and the parent has to be told to 'conduct' child View Models using the ConductWith method, as follows:

public class ParentViewModel : Screen
{
    public ChildViewModel Child { get; set; }

    public ParentViewModel(ChildViewModel childViewModel)
    {
        this.Child = childViewModel;

        Child.ConductWith(this);
    }
}

This ensures the ChildViewModel will be initialized, activated and deactivated at the same time as the parent. The ActivateWith method can be used if you only need to initialize/activate the child.

Rees answered 25/10, 2011 at 6:23 Comment(0)
C
3

The other option is to make the parent a Conductor type and make the child the active item.

Caribou answered 25/10, 2011 at 8:7 Comment(1)
I thought of this, but it seems a bit heavy-handed to make every parent VM a conductor. Nevertheless, it would probably work. To support multiple child view models, Conductor<T>.Collection.AllActive would have to be used.Rees
F
3

Other solution is to use

protected override void OnViewAttached(object view, object context)

instead of OnActivated()

Fluvial answered 6/1, 2013 at 20:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.