开发者

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:

  • Main view is loaded and corresponding view model instantiated
  • In the constructor of the view model I initiate a login sequence that signals when completed with an eventhandler

Now when the login sequence has finished AND the view is completely loaded I need to startup another sequence. But here is the problem, th开发者_如何学Pythone 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.


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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜