Home > database >  Access property in ViewModel from another ViewModel
Access property in ViewModel from another ViewModel

Time:02-05

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:

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.

CodePudding user response:

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);
  }
}
  •  Tags:  
  • Related