5
votes

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 :)

1
Did you set up the Locator in your App.xaml resources (or alternatively, but not as DRY, in your page resources)? Because this looks like it isn't finding the viewmodel in your XAML binding.Robaticus

1 Answers

9
votes

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;
}