2010-08-04 100 views
11

是否可以触发命令来通知窗口已加载。 另外,我没有使用任何MVVM框架(框架在这个意义上,卡利,缟玛瑙,MVVM工具包等)如何在wpf中加载窗口时触发命令

+6

几乎所有事件可能不火ViewModel中的命令。你可以接受这个事实,并在CodeBehind中写入1行代码,或者实现一些模糊的模式,在几行复杂的代码行之后执行相同的操作。 #dontbeapurist – 2010-08-04 18:24:08

+0

我不同意@EduardoMolteni。如果事件与数据工作相关,那么您需要在后面的代码中使用虚拟机,这可以通过WPF中的行为轻松避免。 – JoanComasFdz 2012-12-12 12:44:12

回答

18

为了避免后面的代码在你的浏览,请使用Interactivity库(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);    
    } 
} 
+0

我刚刚意识到这个代码是针对Silverlight的。如果你可以在WPF中找到等价的触发器/行为,我会认为同样的主体应该可以工作。 – programatique 2010-08-04 21:16:54

+1

而不是CommandAction,现在似乎有一个现有的操作,[InvokeCommandAction](http://msdn.microsoft.com/en-us/library/system.windows.interactivity.invokecommandaction(Expression.40).aspx ) – Patrick 2012-05-02 15:59:08

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

和XAML

Loaded="Window_Loaded" 
+2

我忘了提及我正在使用MVVM。何时加载窗口。它应该激发一个命令,我可以在我的ViewModel类中侦听。 – 2010-08-04 17:47:59

+22

MVVM不是一种宗教。你可以在CodeBehind中添加一行代码,这个世界仍然在旋转。 – 2010-08-04 18:28:13

+0

你确定!你确定它会继续旋转吗? :) – GONeale 2012-06-12 05:38:09

2

使用行为一个更通用的方法,提出了在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" 
/>