locked
Access the ViewModel from code behind class RRS feed

  • Frage

  • MVVM pattern. I have a main View with nested child Views. I have a main VM that holds instances of the child VMs. In one of child View, I have to set up the bool property from code behind.

    this.ViewModel.IsSaveButtonVisible = true;

    However I find the NotifyChanged event is null. Maybe I am using a different ViewModel for the binding than I aM using to update the property value. In another word, I may have  multiple ViewModel instances. So in this case, how to access ViewModel from code behind?

    I have

     this.DataContext = this.ViewModel;
    I found the ViewModel was dereferenced during the TAB navigation. In my main View, I have TABs to switch the different Child Views.


    • Bearbeitet ardmore Mittwoch, 5. Oktober 2016 18:20 add
    Mittwoch, 5. Oktober 2016 14:10

Antworten

  • >>So in this case, how to access ViewModel from code behind?

    You can access the ViewModel that is the DataContext of the current view by casting the DataContext property of the view to a ViewModel like this:

    YourViewModelClass viewModel = this.DataContext as YourViewModelClass;
    if(viewModel != null)
    {
    viewModel.IsSaveButtonVisible = true;
    }


    But please provide a reproducible sample of your issue including all relevant code snippets if you want any further help on this. Your issue is a bit unclear.

    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.

    • Als Antwort markiert ardmore Freitag, 7. Oktober 2016 11:02
    Donnerstag, 6. Oktober 2016 21:09