Window_Load event in MVVM

ognale88 picture ognale88 · Sep 3, 2013 · Viewed 15.1k times · Source

I need to write some functions to be executed during the window_load() in WPF-MVVM. Every button will have their own command to be executed. Whereas is there any command available for window_load() event in MVVM Model ?

Answer

Nitin picture Nitin · Sep 3, 2013

You will have to use interactions to do that i.e to invoke command on event.

<Window
    xmlns:intr="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
>
    <intr:Interaction.Triggers>
        <intr:EventTrigger EventName="Loaded">
            <intr:InvokeCommandAction Command="{Binding WindowLoaded}"/>
        </intr:EventTrigger>
    </intr:Interaction.Triggers>
    <!-- the rest of your XAML here -->
</Window>

Window.Interactivity namespace has EventTrigger and InvokeCommandAction.

Don't forget that the WindowLoaded is a property.

public ICommand WindowLoaded { get; set; }

You later have to create new RelayCommand/RoutedUICommand to actually receive the callback.

Thanks