Ryan Searle
Ryan Searle

Reputation: 1627

System.Windows.Controls.UserControl Loaded Event firing when 'Unloaded'

I'm getting a strange phenomenon where the UserControl Loaded Event is firing when the parent window's content control is changing from the current to a new one.

I've tested this behaviour on multiple UserControls and it's happening on all of them.

What I've done:

Window:

<xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"/>

<Controls:TransitioningContentControl Transition="RightReplace" Content="{Binding CurrentViewModel}"/>

When I change the CurrentViewModel Property the corresponding View is loaded into the content control.

UserControl:

<xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"/>

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction Command="{Binding Load, Mode=OneWay}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

When the UserControl is loaded (and for some reason when the UserControl is changed to another) the Load method is run.

Possible Solutions:

There are ways I could work around this for example I could create a Boolean property called ShouldLoad with an if formula in the Load method however this seems rather convoluted for what I'm trying to achieve.

I feel that this behavior should not happen however there is probably an explanation for this...

Upvotes: 2

Views: 866

Answers (2)

Mike Webb
Mike Webb

Reputation: 9003

I'm currently encountering this issue in my app as well.

So far I have found that it has something to do with the <Controls:TransitioningContentControl>, how it is used or where it is placed. I changed my UI to only use <ContentControl> and the multiple Loaded events are not happening anymore for me. It also seems to work as expected for the <Controls:MetroContentControl>.

Upvotes: 1

Ryan Searle
Ryan Searle

Reputation: 1627

This helped me a lot... As it turns out the loaded event gets fired in many circumstances such as when the tab control is changed.

http://blogs.msdn.com/b/mikehillberg/archive/2006/09/19/loadedvsinitialized.aspx

Upvotes: 0

Related Questions