Binding the Loaded event?

后端 未结 5 1148
面向向阳花
面向向阳花 2020-12-24 08:16

I am trying to display a login window once my MainWindow loads while sticking to the MVVM pattern. So I am trying to Bind my main windows Loaded event to an event in my view

5条回答
  •  一生所求
    2020-12-24 08:51

    Use Attached Behavior. That is allowed in MVVM ....

    (code below may / may not compile just like that)

    XAML ...

       
         
         
       
    

    Code Behind...

      class MainWindowViewModel : ViewModelBase
      {
          private ICommand _showLogInWindowCommand;
    
          public ICommand ShowLogInWindowCommand
          {
             get
             {
                  if (_showLogInWindowCommand == null)
                  {
                      _showLogInWindowCommand = new DelegateCommand(OnLoaded)
                  }
                  return _showLogInWindowCommand;
             }
          }
    
          private void OnLoaded()
          {
              //// Put all your code here....
          }
      } 
    

    And the attached behavior...

      public static class MyAttachedBehaviors
      {
          public static DependencyProperty LoadedCommandProperty
            = DependencyProperty.RegisterAttached(
                 "LoadedCommand",
                 typeof(ICommand),
                 typeof(MyAttachedBehaviors),
                 new PropertyMetadata(null, OnLoadedCommandChanged));
    
          private static void OnLoadedCommandChanged
               (DependencyObject depObj, DependencyPropertyChangedEventArgs e)
          {
              var frameworkElement = depObj as FrameworkElement;
              if (frameworkElement != null && e.NewValue is ICommand)
              {
                   frameworkElement.Loaded 
                     += (o, args) =>
                        {
                            (e.NewValue as ICommand).Execute(null);
                        };
              }
          }
    
          public static ICommand GetLoadedCommand(DependencyObject depObj)
          {
             return (ICommand)depObj.GetValue(LoadedCommandProperty);
          }
    
          public static void SetLoadedCommand(
              DependencyObject depObj,
              ICommand  value)
          {
             depObj.SetValue(LoadedCommandProperty, value);
          }
      }
    

    DelegateCommand source code can be found on the internet... Its the most suited ICommand API available for MVVM.

    edit:19.07.2016 two minor syntax errors fixed

提交回复
热议问题