views:

125

answers:

5

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?

+2  A: 

Hi Josh,

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

Damian Schenkelman
A: 

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
        }
Josh Stodola
@HiTech Are you familiar with MVVM? The code-behind for my XAML is bare.
Josh Stodola
Whoops, my mistake. Will delete comments shortly as adding no value.
Enough already
+1  A: 

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.

Brandon Copeland
If you're a fan of his answer, why didn't you upvote it? That's how this is supposed to work.
Josh Stodola
@Josh: True. Done.
Brandon Copeland
A: 

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>
Matthew Paul Keelan
A: 

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().

LittleColin