Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access property in ViewModel from another ViewModel

I have ViewModel with property for displaying notification:

  public class NotificationViewModel : BaseViewModel
  {
    private string errorText;
    public string ErrorText
    {
      get => this.errorText;
      set
      {
        this.errorText = value;
        this.OnPropertyChanged();
      }
    }
  }

Then in MainViewModel.cs I have following command that should display notification in case there is some error:

public NotificationViewModel NotificationViewModel { get; private set; }

public MainViewModel()
{

}

private async Task AddProjectToDatabase()
{
  if (!string.IsNullOrEmpty(this.ProjectNumber))
  {
    // some other code here
  }
  else
  {
    NotificationDialog view = new NotificationDialog
    {
      DataContext = new NotificationViewModel()
    };

    this.NotificationViewModel.ErrorText = "Select project number first!";
    object result = await DialogHost.Show(view, "MainDialogHost", this.ExtendedOpenedEventHandler, this.ExtendedNotificationClosingEventHandler);
  }
}

I have tried to:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public MainViewModel()
{
  this.NotificationViewModel = new NotificationViewModel();
}

However in this case I have no text displayed, as there is now new instance of NotificationViewModel is initialized. I have probably to somehow inject existing instance into MainViewModel.cs ? How I can do that? If there is something missing to privide an answer, please comment.

>Solution :

You can set NotificationViewModel property to DataContext of NotificationDialog.

private async Task AddProjectToDatabase()
{
  if (!string.IsNullOrEmpty(this.ProjectNumber))
  {
    // some other code here
  }
  else
  {
    NotificationDialog view = new NotificationDialog
    {
      DataContext = this.NotificationViewModel
    };

    this.NotificationViewModel.ErrorText = "Select project number first!";
    object result = await DialogHost.Show(view, "MainDialogHost", this.ExtendedOpenedEventHandler, this.ExtendedNotificationClosingEventHandler);
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading