3
votes

I am new to Silverlight (version 4) and MVVM, and I can't seem to figure out how to bind a command in the XAML to my ViewModel for the "Loaded" event of a UserControl. I can bind a command to a button like this...

<Button Command="{Binding ShowImageClick}" />

And it works fine. But I have no idea how to do something similiar onload. I tried this but it threw an exception saying "Failed to assign property"...

<UserControl Loaded="{Binding WindowLoad}">

Any ideas?

6

6 Answers

2
votes

One possible approach could be using this code snippet I created to hook-up commands with events using Attached Behaviors.

I hope this helps.

Thanks, Damian

2
votes

The Expression Blend Samples project on Codeplex may be helpful:

Expression Blend Samples

e.g.:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <si:InvokeDataCommand Command="{Binding Command}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>
1
votes

I'm a fan of Damian's answer and would typically use that solution.

Another common practice is the InvokeCommandAction or similar behavior in Blend.

0
votes

Not sure if this is best practice or not, but simply having a constructor in the ViewModel class seems to work well enough for me...

namespace App.ViewModels
{
    public class Main : INotifyPropertyChanged
    {

        public Main()
        {
            // Onload code here
        }
0
votes

I just found that can cause a memory leak and have reverted to old-school Loaded. To check this, add a finalizer to your user control/page and ensure it is called when you do a GC.Collect().

0
votes

Maybe this helps its not the proper way but it works for me.

View:

<UserControl Tag="{Binding InitializeMyUserControl}">

View Model:

public object InitializeMyUserControl
{
    get
    {
        // do some initialization in here
        // bla bla bla
        .. 

        return null;
    }
}

when UserControl loads it will try to get the tag value. In there you can initialize things.