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