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

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

问题描述

是否可以触发一个命令来通知窗口已加载.此外,我没有使用任何 MVVM 框架(某种意义上的框架,Caliburn、Onxy、MVVM 工具包等)

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

推荐答案

为了避免代码隐藏在您的视图中,请使用交互库(您可以从 Microsoft 免费下载的 System.Windows.Interactivity dll - 也随 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天全站免登陆