从另一个ViewModel访问ViewModel中的属性



我有ViewModel,其属性用于显示通知:

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

然后在MainViewModel.cs中,我有以下命令,如果出现错误,应该显示通知:

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

我试过:

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

然而,在这种情况下,我没有显示任何文本,因为现在有一个NotificationViewModel的新实例已初始化。我可能不得不以某种方式将现有实例注入MainViewModel.cs?我该怎么做?如果有什么遗漏,请发表评论。

您可以将NotificationViewModel属性设置为NotificationDialogDataContext

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

最新更新