Search code examples
wpfviewrenderviewmodeleventtrigger

WPF, `Loaded` event is only fired on first viewmodel initialization but not subsequent ones


I initialize the view model of a UserControl multiple times like this

ChartControl = new SciChartControlViewModel(true, false, true);

The view is rendered via ContentControl like

<Grid Grid.Row="1">
     <ContentControl Content="{Binding ChartControl}"/>
</Grid>

I hook into the Loaded event within the view like this

<i:Interaction.Triggers>

    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction Command="{Binding OnViewLoadedCommand}"/>
    </i:EventTrigger>

</i:Interaction.Triggers>

Problem: Only on the first initialization of the view model does the Loaded event fire. When I subsequently initialize the view model again the Loaded event is not fired anymore. Only when the control loses focus and is brought back into focus it fires.

Desired Behavior: How can I make sure that I capture in my view model each time when the view is entirely rendered? I need to capture this because some operations I perform in my view model on this control only work when the view is fully rendered.


Solution

  • The problem is, that the view is initialized (and loaded) once and will be reused when changing the content.

    You could try to use the DataContextChanged event - Not sure if that works if you bound to the Content property. Otherwise you could overwrite the metadata for Content dependency property as descibed here.