Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVMLight - how to get a reference to the ViewModel in the View?

I'm building a Windows Phone 7 app, and I need a reference to my ViewModel in my view so I can set a property from my event handler. The only problem is that I'm not able to get that reference.

What I did;

I have a ViewModelLocator (deleted the irrelevant bits):

static ViewModelLocator()
{
    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

    SimpleIoc.Default.Register<TunerViewModel>();
}

[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This non-static member is needed for data binding purposes.")]
public TunerViewModel Tuner
{
    get { return ServiceLocator.Current.GetInstance<TunerViewModel>(); }
}

And a view (XAML):

DataContext="{Binding Tuner, Source={StaticResource Locator}}">

And the code-behind of the view:

public partial class Tuner : PhoneApplicationPage
{
    private readonly TunerViewModel _viewModel;

    public Tuner()
    {
        _viewModel = DataContext as TunerViewModel;

        InitializeComponent();
    }

I found this link MVVM View reference to ViewModel where the DataContext is casted to a ViewModel, so I tried the same because it looks like a good solution. However, my _viewModel field is null after the cast. Why is this and how do I fix this? I couldn't find it on Google/Stackoverflow

Thanks in advance :)

like image 390
Leon Cullens Avatar asked Mar 20 '12 15:03

Leon Cullens


1 Answers

Because you set the DataContext from XAML with a binding expression in the View's constructor the DataContext is not set yet. That's why you get null.

Try the cast the DataContext in or after the Loaded event:

public Tuner()
{
    InitializeComponent();
    Loaded += OnTunerLoaded;
}

private void OnTunerLoaded(object sender, RoutedEventArgs routedEventArgs)
{
    _viewModel = DataContext as TunerViewModel;
}
like image 83
nemesv Avatar answered Nov 15 '22 10:11

nemesv