窗口加载和WPF

我在Windows 2012中有一个WPF项目,我需要在Window Loaded事件中加载一些信息。 不过,我需要在View Model中而不是在CodeBehind中执行此操作。 我试图使用以下代码:

在我的xaml中:

   

在我的视图模型中:

 private DelegateCommand _WindowLoadedCommand; public DelegateCommand WindowLoadedCommand { get { return _WindowLoadedCommand; } private set { _WindowLoadedCommand = value; } } public ShellViewModel() { WindowLoadedCommand = new DelegateCommand(WindowLoadedAction); } protected void WindowLoadedAction() { ... } 

我附加的行为:

 public class WindowLoadedBehavior : Behavior { [SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1401:FieldsMustBePrivate", Justification = "Dependency Property. Allow public.")] public static DependencyProperty LoadedCommandProperty = DependencyProperty.Register("LoadedCommand", typeof(ICommand), typeof(WindowLoadedBehavior), new PropertyMetadata(null)); public ICommand LoadedCommand { get { return (ICommand)GetValue(LoadedCommandProperty); } set { SetValue(LoadedCommandProperty, value); } } protected override void OnAttached() { base.OnAttached(); AssociatedObject.Loaded += AssociatedObject_Loaded; } protected override void OnDetaching() { AssociatedObject.Loaded -= AssociatedObject_Loaded; base.OnDetaching(); } private void AssociatedObject_Loaded(object sender, RoutedEventArgs e) { if (LoadedCommand != null) LoadedCommand.Execute(null); } } 

OnAttached,AssociatedObject_Loaded和LoadedCommand get都被触发,但是LoadedCommand集没有触发,显然,WindowLoadedCommand没有触发。 任何线索我能做些什么来使这个工作?

有几个选择。 其中一些列在这里:

如何在WPF MVVM中调用窗口的Loaded事件?

但是,如果您或其他任何人担心您花费几个小时完成一项应该花费30秒的任务,那么您可能希望尝试这样做。

 public MainWindow() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainWindow_Loaded); } void MainWindow_Loaded(object sender, RoutedEventArgs e) { ShellViewModel.Instance.WindowLoadedCommand.Execute(null); }