views:

52

answers:

3

Is it possible to fire a command to notify the window is loaded. Also, I'm not using any MVVM frameworks (Frameworks in the sense, Caliburn, Onxy, MVVM Toolkit etc.,)

+3  A: 
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
       ApplicationCommands.New.Execute(null, targetElement); 
       // or this.CommandBindings[0].Command.Execute(null); 
    }

and xaml

    Loaded="Window_Loaded"
lukas
I forgot to mention I'm using MVVM. When, a window is loaded. It should fire a command, that I'll be able to listen in my ViewModel class.
Avatar
MVVM is not a religion. You can add a line of code in the CodeBehind and the world will still be spinning.
Eduardo Molteni
A: 

Your window will file an event on its own when it is loaded. You can handle it by delegating to a method that you define.

For example:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Hello World!", "Window.Loaded Handler", MessageBoxButton.OK);
    }
}
Brian Driscoll
+1  A: 

To avoid code behind on your View, use the Interactivity library (System.Windows.Interactivity dll which you can download for free from Microsoft - also comes with Expression Blend).

Then you can create a behavior that executes a command. This way the Trigger calls the Behavior which calls the Command.

<ia:Interaction.Triggers>
    <ia:EventTrigger EventName="Loaded">
        <custombehaviors:CommandAction Command="{Binding ShowMessage}" Parameter="I am loaded"/>
    </ia:EventTrigger>
</ia:Interaction.Triggers>

CommandAction (also uses System.Windows.Interactivity) can look like:

public class CommandAction : TriggerAction<UIElement>
{
    public static DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandAction), null);
    public ICommand Command
    {
        get
        {
            return (ICommand)GetValue(CommandProperty);
        }
        set
        {
            SetValue(CommandProperty, value);
        }
    }


    public static DependencyProperty ParameterProperty = DependencyProperty.Register("Parameter", typeof(object), typeof(CommandAction), null);
    public object Parameter
    {
        get
        {
            return GetValue(ParameterProperty);
        }
        set
        {
            SetValue(ParameterProperty, value);

        }
    }

    protected override void Invoke(object parameter)
    {
        Command.Execute(Parameter);            
    }
}
programatique
I just realized this code is for Silverlight. If you can find the equivalent trigger/behaviors in WPF, I would think the same principals should work though.
programatique