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

Pri*_*aka 11 wpf mvvm commandbinding delegatecommand

是否可以触发命令以通知窗口已加载.另外,我没有使用任何MVVM框架(在某种意义上的框架,Caliburn,Onxy,MVVM Toolkit等)

pro*_*que 18

要避免View上的代码,请使用Interactivity库(System.Windows.Interactivity dll,您可以从Microsoft免费下载 - 也随Expression Blend一起提供).

然后,您可以创建执行命令的行为.这样,Trigger调用调用Command的Behavior.

<ia:Interaction.Triggers>
    <ia:EventTrigger EventName="Loaded">
        <custombehaviors:CommandAction Command="{Binding ShowMessage}" Parameter="I am loaded"/>
    </ia:EventTrigger>
</ia:Interaction.Triggers>
Run Code Online (Sandbox Code Playgroud)

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);            
    }
}
Run Code Online (Sandbox Code Playgroud)


Luk*_*don 7

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
       ApplicationCommands.New.Execute(null, targetElement); 
       // or this.CommandBindings[0].Command.Execute(null); 
    }
Run Code Online (Sandbox Code Playgroud)

和xaml

    Loaded="Window_Loaded"
Run Code Online (Sandbox Code Playgroud)

  • MVVM不是宗教.你可以在CodeBehind中添加一行代码,世界仍然在旋转. (23认同)
  • 只要该行代码只是视图的责任.:) (4认同)
  • 我忘了提到我正在使用MVVM.何时加载窗口.它应该触发一个命令,我将能够在我的ViewModel类中监听. (2认同)