Bind.Model problem with Message.Attach

Oct 8, 2010 at 7:31 PM

I use followin code to bind the viewmodel to view, but the TextBox_Loaded action was called before the viewmodel attached to the view,
and raise exception "No target found for method TextBox_Loaded.."

What's wrong with my code ?


<UserControl x:Class="Caliburn.Micro.HelloMef.TestView"

    <Grid x:Name="LayoutRoot"
        <Rectangle Fill="red" />
        <TextBox cal:Message.Attach="[Event Loaded]=[Action TextBox_Loaded($source,$eventArgs)]"
                 VerticalAlignment="Center" />

namespace Caliburn.Micro.HelloMef
    [Export("TestViewModel", typeof(TestViewModel))]
    public class TestViewModel
        public TestViewModel()

        public void TextBox_Loaded(object sender, RoutedEventArgs e)


Oct 8, 2010 at 8:48 PM

I checked the source code; the creation of the ViewModel and the binding with the view actually occurs exactly when Loaded event is raised:

handler = delegate{
                var target = e.NewValue;
                var containerKey = e.NewValue as string;

                if (containerKey != null)
                    target = IoC.GetInstance(null, containerKey);

                d.SetValue(View.IsLoadedProperty, true);
                ViewModelBinder.Bind(target, d, null);
                fe.Loaded -= handler;

            fe.Loaded += handler;

I don't know the rationale behind it. Anyway you be able to run the initialization code in TestViewModel contructor.
This may also help to keep the VM interface and code free from UI-related components.

Oct 8, 2010 at 9:27 PM

For some very technical reasons (most of which I forgot by now) we cannot correctly make Bind.Model work until Loaded is fired. I recommend that you implement your init logic either in your VM's constructor or you do it by overriding OnInitialize if you are inheriting from Screen. BTW, what you are doing in code and markup is *very* strange. It makes your VM look like a code-behind file...

Oct 8, 2010 at 9:44 PM
Edited Oct 8, 2010 at 9:58 PM

The reason I use TextBox's Loaded event is that binding to ActualHeight don't always work. so  I save TextBox's ActualHeight in the loaded event.


Oct 8, 2010 at 10:08 PM

My advice on that would be to put that logic in the code-behind. View-specific code is what that's for. Keep that separate from your view models.