在WPF中加载窗口时如何触发命令 [英] How to fire a Command when a window is loaded in wpf

查看:587
本文介绍了在WPF中加载窗口时如何触发命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.,)

推荐答案

为避免在视图上隐藏代码,请使用Interactivity库(System.Windows.Interactivity dll,您可以从Microsoft免费下载该库-Expression Blend附带了该库).

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.

<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)看起来像:

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

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);            
    }
}

这篇关于在WPF中加载窗口时如何触发命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆