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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 03:33:30

问题


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:


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


来源:https://stackoverflow.com/questions/9789508/mvvmlight-how-to-get-a-reference-to-the-viewmodel-in-the-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!