Caliburn.Micro - doing something when a view becomes visible
Asked Answered
F

1

6

I am currently getting into WPF and Caliburn.Micro ,for now without something like MEF or Autofac.

Right now i am trying to execute some code in a viewmodel right after its view becomes visible.

In a related tutorial this code displays a messagebox just before a view is shown:

protected override void OnActivate() 
{   
    MessageBox.Show("Page Two Activated"); //Don't do this in a real VM.   
    base.OnActivate();   
}  

Mr. Eisenberg then writes this:

Remember, if you have any activation logic that is dependent on the view being already loaded, you should override Screen.OnViewLoaded instead of/in combination with OnActivate.

This is what i have:

protected override void OnViewLoaded(object view)
{
    base.OnViewLoaded(view);
    MessageBox.Show("OnPageTwoViewLoaded");
}

I also tried it via a Grid EventTrigger and a cal:ActionMessage. But in all three cases the MessageBox appears before the view is visible.

Surely i am missing something, what am i doing wrong?

Fishhook answered 28/10, 2011 at 16:48 Comment(3)
C.M creates your view instances before you actually see them on the screen. (That is, C.M does not lazy load these) So the OnViewLoaded code is run before you actually see the view. I think OnActivate should be the correct place for it, not OnViewLoaded. Did you try and sandbox this particular behavior?Perplexity
Thanks for your answer. I don't know what you mean by sandbox this but if i put the MessageBox code in OnActivate it also gets shown before the view is visible. If i put it in my overidden OnViewAttached it forces OnViewLoaded to be executed sooner leading TO something that appears to work. However if i put other code in there it still gets executed before the view is visible.Fishhook
@Perplexity , so when does CM actually instanciate a VIEW? Does it instanciate them all on startup?Rupe
M
2

Maybe not the most elegant solution, but I guess you can do this from the code-behind, since - strictly speaking - this is a very view/gui specific thing you're trying to do here. For instance in OnInitialized or OnRender. If you give your view a reference to the EventAggregator, you could raise an event and make the view model - or whatever class you want, subscribe to this event and do it's thing. Or in the case of showing a MessageBox, you really wouldn't have that any place else than in the View anyway.

Metaprotein answered 30/10, 2011 at 21:26 Comment(2)
Those don't work for me either. Caliburns OnViewAttached seems closest to what i like, i'll see if thats good enough or if i go at it from out side of that viewmodel/view .Fishhook
OnViewLoaded seems to be best choice for OnShownUlloa

© 2022 - 2024 — McMap. All rights reserved.