Depechie
Depechie

Reputation: 6142

MVVM - View loading and eventhandling

In my windows phone app, I need to track some events to get a good flow. But I'm not sure how to handle them in good sequence.

What needs to be done at startup of the app:

Now when the login sequence has finished AND the view is completely loaded I need to startup another sequence. But here is the problem, the order of these 2 events 'completing' is not always the same... I've use the EventToCommand from MVVMLight to signal the view model that the view has 'loaded'.

Any thoughts on how to synchronize this.

Upvotes: 2

Views: 260

Answers (1)

AxelEckenberger
AxelEckenberger

Reputation: 16926

As you should not use wait handles or something similar on the UI thread. You will have to sync the two method using flags in your view model and check them before progressing.

So, implement two boolean properties in your view model. Now when the login dialog is finished set one of the properties (lets call it IsLoggedIn) to true, and when the initialization sequence is finished you set the other property (how about IsInitialized) to true. The trick now lies in the implementation of the setter of these two properties:

#region [IsInitialized]

public const string IsInitializedPropertyName = "IsInitialized";

private bool _isInitialized = false;

public bool IsInitialized {
    get {
        return _isInitialized;
    }
    set {
        if (_isInitialized == value)
            return;

        var oldValue = _isInitialized;
        _isInitialized = value;

        RaisePropertyChanged(IsInitializedPropertyName);

        InitializationComplete();
    }
}

#endregion

#region [IsLoggedIn]

public const string IsLoggedInPropertyName = "IsLoggedIn";

private bool _isLoggedIn = false;

public bool IsLoggedIn {
    get {
        return _isLoggedIn;
    }
    set {
        if (_isLoggedIn == value) 
            return;

        var oldValue = _isLoggedIn;
        _isLoggedIn = value;

        RaisePropertyChanged(IsLoggedInPropertyName);

        InitializationComplete();
    }
}

#endregion

public void InitializationComplete() {
    if (!(this.IsInitialized && this.IsLoggedIn))
        return;

    // put your code here
}

Alternatively you can remove the InitializationComplete from the setters and change InitializationComplete to:

public void InitializationComplete() {
    // put your code here
}

Then subscribe to the 'PropertyChanged' event use the following implementation:

private void Class1_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) {
    if (e.PropertyName == IsInitializedPropertyName || e.PropertyName == IsLoggedInPropertyName) {
        if (this.IsInitialized && this.IsLoggedIn)
            InitializationComplete();
    }
}

Upvotes: 1

Related Questions