简体   繁体   中英

MVVM light RelayCommand triggers twice

I'm working on a new c# MVVM light modern ui WPF application and I ran into some weird trigger behavior. So to describe the situation, here is the following:

I have an XML view with triggers. (Loaded method as example)

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction Command="{Binding LoadedCommand}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

The constructor with the relaycommand (LoadedCommand from abstract model)

    public MovieListModel()
    {
        LoadedCommand = new RelayCommand(LoadData);
    }        
    private void LoadData()
    {
        Debug.WriteLine("MovieListModel - LoadData");
    }

Problem: When the application starts the loadedcommand is called 1 time (good). When I navigate to an other page inside the application, then both the first and the new view LoadedCommand's are triggered. Other commands are also triggered twice. I am guessing this will become a problem if I want to put some programming logic inside later on.

The full debug.writeline is as followed:

ModernUserControl - OnNavigatingFrom
MovieListModel - NavigatingFrom
ModernUserControl - OnNavigatingFrom event called
ModernUserControl - OnNavigatedFrom
MovieListModel - NavigatedFrom
ModernUserControl - OnNavigatedFrom event called
ModernUserControl - OnNavigatedTo
MovieListModel - LoadData
SettingsModel - LoadData

Info: I found this problem in the example program found here: https://github.com/saramgsilva/ModernUISamples and in my own application. I also started a ticket on github to find out if this is a problem/bug or not. (no reply yet)

I would recommend avoiding the Loaded event in WPF for code that is only supposed to run once.

WPF unloads controls which are not in use (such as if the application is minimized, or you change tab pages), so the Loaded command will often run more than once.

If code is meant to only run once, I typically will either put it in the Constructor or lazy-load data in the getter.

And if I really want to use the Loaded event for something that is only meant to run once, I will make sure to detach the event from within the Loaded event handler when it runs the first time.

The loaded event is triggered twice.

Read this blog post explaining it: http://blogs.msdn.com/b/mikehillberg/archive/2006/09/19/loadedvsinitialized.aspx

Or even better, read this answer from another post: Loaded event of a WPF user control fire two times

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM