我正在做的事情是在视图模型中需要发生很多事情,但是当视图被加载时,而不是在构造函数上。我可以连接事件处理程序并发送消息,但这对我来说似乎有点草率。我正在实现一个包含此逻辑的基本视图和基本视图模型,因此我的所有视图都默认获得它,希望如此。
也许我什至无法得到我想要的东西:发件人。我只是想这是 RoutedEventArgs.OriginalSource 应该是什么?
[编辑] 与此同时,我在 xaml.cs 中连接了一个 EventHandler,果然,OriginalSource 在那里也是空的。所以我想我真的需要知道是否有可能在命令中获得对视图/发送者的引用?[/编辑]
我的实现要求我的视图模型的帮助器类负责创建“窗口”,该类知道所有窗口都添加到的“主机”控件。我愿意接受在使用 eventtocommand 的范围之外完成此任务的建议。:)
(Unloaded 的代码是一样的)
#region ViewLoadedCommand
private RelayCommand<RoutedEventArgs> _viewLoadedCommand = null;
/// <summary>
/// Command to handle the control's Loaded event.
/// </summary>
public RelayCommand<RoutedEventArgs> ViewLoadedCommand
{
get
{
// lazy-instantiate the RelayCommand on first usage
if (_viewLoadedCommand == null)
{
_viewLoadedCommand = new RelayCommand<RoutedEventArgs>(
e => this.OnViewLoadedCommand(e));
}
return _viewLoadedCommand;
}
}
#endregion ViewLoadedCommand
#region View EventHandlers
protected virtual void OnViewLoadedCommand(RoutedEventArgs e)
{
EventHandler handler = ViewLoaded;
if (handler != null)
{
handler(this, e);
}
}
#endregion