为了说明@mvermef 的评论:
在 3 个类对象之间使用一个通用类型,显然创建这个类型有问题
这将是第一个视图模型填充并由第二个视图模型使用的 connection 对象。
public class Connection {
// props, methods, etc...
}
并在构造函数中传递它或使其成为所有 3 个类的属性
public class ShellViewModel : Conductor<IScreen>, IShell
{
public Connection Connection { get; set; }
public ShellViewModel()
{
Connection = new Connection();
ShowConnectionScreen();
}
public void ShowConnectionScreen()
{
ActivateItem(new ConnectionViewModel(Connection));
}
public void ShowSetupScreen()
{
ActivateItem(new SetupViewModel(Connection));
}
}
使用 ConnectionViewModel 中的 Connection 对象做你想做的事
public class ConnectionViewModel : Screen
{
public Connection Connection { get; set; }
// establish connection
// can call (Parent as IConductor).DeactivateItem(this)
// after connection is established
}
您可以通过 (1) 通过 ConnectionViewModel 的 Deactivated 事件(假设您是 Screen 的子类)注册来通知父导体是否建立了连接。或者 (2) 如果连接已建立并让 ShellViewModel 实现 IHandle,您可以使用 EventAggregator 触发事件。然后,您可以在 Deactivated 事件处理程序或 Handle 方法中调用 ShowSetupScreen()。
选项 1:
// ShellViewModel
public void ShowConnectionScreen()
{
var connectionVM = new ConnectionViewModel();
connectionVM.Deactivated += ConnectionViewModel_Deactivated;
ActivateItem();
}
private void Scheduler_Deactivated1(object sender, DeactivationEventArgs e)
{
ShowSetupScreen();
}
选项 2:
public class ShellViewModel : Conductor<IScreen>,
IShell, IHandle<string>
{
private readonly IEventAggregator _eventAggregator;
public ShellViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
_eventAggregator.Subscribe(this);
}
// from IHandle<string>. you can create a custom object to represent this event
public void Handle(string message)
{
if (message.Equals("connection.successful"))
{
ShowSetupScreen();
}
}
}
public class ConnectionViewModel : Screen
{
private readonly IEventAggregator _eventAggregator;
public ConnectionViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}
// call _eventAggregator.PublishOnUIThread("connection.successful");
}