How to fire a Command when a window is loaded in wpf

前端 未结 4 1437
Happy的楠姐
Happy的楠姐 2020-12-14 23:08

Is it possible to fire a command to notify the window is loaded. Also, I\'m not using any MVVM frameworks (Frameworks in the sense, Caliburn, Onxy, MVVM Toolkit etc.,)

4条回答
  •  感动是毒
    2020-12-14 23:32

    To avoid code behind on your View, use the Interactivity library (System.Windows.Interactivity dll which you can download for free from Microsoft - also comes with Expression Blend).

    Then you can create a behavior that executes a command. This way the Trigger calls the Behavior which calls the Command.

    
        
            
        
    
    

    CommandAction (also uses System.Windows.Interactivity) can look like:

    public class CommandAction : TriggerAction
    {
        public static DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandAction), null);
        public ICommand Command
        {
            get
            {
                return (ICommand)GetValue(CommandProperty);
            }
            set
            {
                SetValue(CommandProperty, value);
            }
        }
    
    
        public static DependencyProperty ParameterProperty = DependencyProperty.Register("Parameter", typeof(object), typeof(CommandAction), null);
        public object Parameter
        {
            get
            {
                return GetValue(ParameterProperty);
            }
            set
            {
                SetValue(ParameterProperty, value);
    
            }
        }
    
        protected override void Invoke(object parameter)
        {
            Command.Execute(Parameter);            
        }
    }
    

提交回复
热议问题