代码之家  ›  专栏  ›  技术社区  ›  Prince Ashitaka

如何在wpf中加载窗口时触发命令

  •  11
  • Prince Ashitaka  · 技术社区  · 15 年前

    另外,我没有使用任何MVVM框架(即Caliburn、Onxy、mvvmtoolkit等意义上的框架)

    3 回复  |  直到 15 年前
        1
  •  18
  •   programatique    15 年前

    要避免视图中的代码落后,请使用交互库(System.Windows.Interactivity dll,您可以从Microsoft免费下载-Expression Blend也提供了该库)。

    <ia:Interaction.Triggers>
        <ia:EventTrigger EventName="Loaded">
            <custombehaviors:CommandAction Command="{Binding ShowMessage}" Parameter="I am loaded"/>
        </ia:EventTrigger>
    </ia:Interaction.Triggers>
    

    CommandAction(也使用System.Windows.Interactivity)可以如下所示:

    public class CommandAction : TriggerAction<UIElement>
    {
        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);            
        }
    }
    
        2
  •  7
  •   Lukasz Madon    15 年前
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
           ApplicationCommands.New.Execute(null, targetElement); 
           // or this.CommandBindings[0].Command.Execute(null); 
        }
    

    和xaml

        Loaded="Window_Loaded"
    
        3
  •  2
  •   JoanComasFdz    13 年前

    AttachedCommandBehavior V2 aka ACB 它甚至支持多个事件到命令绑定,

    下面是一个非常基本的使用示例:

    <Window x:Class="Example.YourWindow"
            xmlns:local="clr-namespace:AttachedCommandBehavior;assembly=AttachedCommandBehavior"
            local:CommandBehavior.Event="Loaded"
            local:CommandBehavior.Command="{Binding DoSomethingWhenWindowIsLoaded}"
            local:CommandBehavior.CommandParameter="Some information"
    />
    
        4
  •  1
  •   dasch88    5 年前

    xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    

    像这样利用它:

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <i:InvokeCommandAction Command="{Binding CommandInViewModel}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>