首页 \ 问答 \ 如何使用InvokeCommandAction调用我的方法并传入参数?(How do I go about using InvokeCommandAction to call a method of mine and pass in parameters?)

如何使用InvokeCommandAction调用我的方法并传入参数?(How do I go about using InvokeCommandAction to call a method of mine and pass in parameters?)

我一直试图弄清楚如何从Loaded=""事件传递参数。 我在这里问了一个问题: 如何在Loaded =“”上传递参数? 并被引导到InvokeCommandAction的方向。

问题是我无法弄清楚如何实际使用InvokeCommandAction来调用我的方法。 我的XAML:

        <Expander x:Name="Greeting_And_Opening_Expander" ExpandDirection="Down" IsExpanded="True" FontSize="14" FontWeight="Bold" Margin="5" BorderThickness="1" BorderBrush="#FF3E3D3D">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Loaded">
                    <i:InvokeCommandAction Command="{Binding ExpanderLoaded}"
                                           CommandParameter="x:Static local:Sections.Opening"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>

我在后面的代码中有一个名为ExpanderLoaded的方法,如下所示:

    private void ExpanderLoaded(object sender, RoutedEventArgs e, Sections section)
    {
        //Do Stuff
    }

和同一名称空间下的枚举:

public enum Sections
{
    Default = 0,
    Opening = 1,
    Verify = 2
}

使用上面发布的XAML调用我的方法需要做什么? 我是WPF的新手,所以如果我最后问起什么似乎是愚蠢的问题,请试着忍受我。 我浏览了stackoverflow阅读其他类似的问题,并且无法获得足够的信息继续我自己。


I've been trying to figure out how to pass parameters from the Loaded="" event. I asked a question here: How would I go about passing a parameter on Loaded=" "? and was guided in the direction of InvokeCommandAction.

Issue is I am unable to figure out how to actually use the InvokeCommandAction to call my method. My XAML:

        <Expander x:Name="Greeting_And_Opening_Expander" ExpandDirection="Down" IsExpanded="True" FontSize="14" FontWeight="Bold" Margin="5" BorderThickness="1" BorderBrush="#FF3E3D3D">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Loaded">
                    <i:InvokeCommandAction Command="{Binding ExpanderLoaded}"
                                           CommandParameter="x:Static local:Sections.Opening"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>

I have a method named ExpanderLoaded in the code behind that goes as follows:

    private void ExpanderLoaded(object sender, RoutedEventArgs e, Sections section)
    {
        //Do Stuff
    }

And an Enum under the same namespace:

public enum Sections
{
    Default = 0,
    Opening = 1,
    Verify = 2
}

What do I need to do to call my method using the XAML I posted above? I am very new to WPF, so please try and bear with me if I end up asking what seem to be stupid questions. I've browsed around stackoverflow reading other similar questions and have been unable to gleam enough information to continue on my own.


原文:https://stackoverflow.com/questions/30494035
更新时间:2020-11-02 17:11

最满意答案

命令绑定需要一个实现ICommand接口的具体实例。 您绑定到方法名称,它根本不会真正绑定。 命令绑定意味着在MVVM设计中的ViewModel类中使用,但是从您的示例代码中可以看出,您在Xaml视图的代码隐藏中使用它。 如果你想坚持代码隐藏,只需使用事件处理程序。

有关ICommand实现的很多示例,您也可以在Prism中使用现成的DelegateCommand 。 我在下面展示了一个简单的示例,该示例实现了一个非常基本的ICommand,只要您的View和ViewModel已连线,它就可以用于您要执行的操作。

    //Very basic ICommand implementation    
    public class RelayCommand : ICommand
    {
        private Action<object> command;
        private Func<bool> canExecute;

        public RelayCommand(Action<object> commandAction, Func<bool> canExecute = null)
        {
            this.command = commandAction;
            this.canExecute = canExecute;
        }

        /// <summary>
        /// Returns default true. 
        /// Customize to implement can execute logic.
        /// </summary>
        public bool CanExecute(object parameter)
        {
            return this.canExecute == null ? true : this.canExecute();
        }

        /// <summary>
        /// Implement changed logic if needed
        /// </summary>
        public event EventHandler CanExecuteChanged;


        public void Execute(object parameter)
        {            
            if (this.command != null)
            {
                this.command(parameter);
            }
        }
    }

    //Example of a view model
    public class MyViewModel
    {
        public MyViewModel()
        {
            this.ExpanderCommand = new RelayCommand(this.ExecuteExpanderCommand);
        }

        // This property will be the command binding target
        public RelayCommand ExpanderCommand { get; set; }

        // this is the handler method
        public void ExecuteExpanderCommand(object parameter)
        {
            var section = (Sections)parameter;
            //do your stuff here
        }
    }

Xaml绑定:

<i:EventTrigger EventName="Loaded">
 <i:InvokeCommandAction Command="{Binding ExpanderCommand}"
                                               CommandParameter="x:Static local:Sections.Opening"/>
</i:EventTrigger>

Command Binding requires a concrete instance that implements ICommand interface. You are binding to a method name, which will not really bind at all. Command binding is meant to be used in ViewModel class within MVVM design, but from your sample code it seems you are using it within code-behind of the Xaml view. If you want to stick to code-behind, just use event handler.

There are lot of examples on ICommand implementation, you can also use out of the box DelegateCommand available in Prism. I am showing a simple example below which implements a very basic ICommand that will work for what you are trying to do as long as your View and ViewModel is wired up.

    //Very basic ICommand implementation    
    public class RelayCommand : ICommand
    {
        private Action<object> command;
        private Func<bool> canExecute;

        public RelayCommand(Action<object> commandAction, Func<bool> canExecute = null)
        {
            this.command = commandAction;
            this.canExecute = canExecute;
        }

        /// <summary>
        /// Returns default true. 
        /// Customize to implement can execute logic.
        /// </summary>
        public bool CanExecute(object parameter)
        {
            return this.canExecute == null ? true : this.canExecute();
        }

        /// <summary>
        /// Implement changed logic if needed
        /// </summary>
        public event EventHandler CanExecuteChanged;


        public void Execute(object parameter)
        {            
            if (this.command != null)
            {
                this.command(parameter);
            }
        }
    }

    //Example of a view model
    public class MyViewModel
    {
        public MyViewModel()
        {
            this.ExpanderCommand = new RelayCommand(this.ExecuteExpanderCommand);
        }

        // This property will be the command binding target
        public RelayCommand ExpanderCommand { get; set; }

        // this is the handler method
        public void ExecuteExpanderCommand(object parameter)
        {
            var section = (Sections)parameter;
            //do your stuff here
        }
    }

Xaml binding:

<i:EventTrigger EventName="Loaded">
 <i:InvokeCommandAction Command="{Binding ExpanderCommand}"
                                               CommandParameter="x:Static local:Sections.Opening"/>
</i:EventTrigger>

相关问答

更多

如何以编程方式使用EventTrigger和InvokeCommandAction?(How to use EventTrigger and InvokeCommandAction programmatically?)

您可以使用InputBindings - KeyBinding作为替代方法。 像这样的东西: <TextBox x:Name="TicketNumber"> <TextBox.InputBindings> <KeyBinding Key="Enter" Command="{Binding OpenTicketCommand}" CommandParameter="{Binding Elemen ...

XAML Hub Control Windows 8.1 Universal,InvokeCommandAction未触发(XAML Hub Control Windows 8.1 Universal, InvokeCommandAction not firing)

您必须对拥有ViewModel的页面进行引用。 为您的页面设置一个名称,例如:“pageRoot”然后将您的行为更改为 <interactivity:Interaction.Behaviors> <core:EventTriggerBehavior EventName="Tapped"> <core:InvokeCommandAction Command="{Binding DataContext.ViewMoreCommand, ElementName=pageRoot} ...

在方法名称之间传递参数(Pass parameters between method name)

当然,还有Smalltalk,它的关键字消息非常具有表现力...... n := collection size // 2. head := collection copyFrom: 1 to: n. 除此之外,您会发现在ADA或Python中,可能还有其他一些您可以在每个参数前面加上一个键(应与函数参数名称匹配)... Of course, there is Smalltalk which is really expressive with its keyword messages... n ...

将方法作为参数传递给传入方法的零个或多个参数?(Passing a method as a parameter with zero or more parameters for the passed in method?)

你必须使用代表。 // rewrite your trigger constructor like this class MyTrigger<TTarget> { public MyTrigger(TTarget target, Action<TTarget> action); public void Activate() { this._action(this._target); } } // now call it with or withou ...

DataGridTemplateColumn InvokeCommandAction模板(DataGridTemplateColumn InvokeCommandAction Template)

如果您的DataTemplate完全相同,那么只需将其放入Resources部分,然后简单地引用它: <DataGrid.Resources> <DataTemplate x:Key="TheDataTemplate"> <TextBlock Background="{Binding _5_5, Converter={StaticResource ResourceKey=hourSlotColorConverter}, UpdateSourceTr ...

MVVMCross Behaviors和InvokeCommandAction(MVVMCross Behaviours and InvokeCommandAction)

使用InvokeCommandAction的InputConverter属性解决 <interactivity:Interaction.Behaviors> <icore:EventTriggerBehavior EventName="ItemClick"> <icore:InvokeCommandAction Command="{Binding SelectModuleComm ...

ListView MVVM中的TextBox上的UWP InvokeCommandAction(UWP InvokeCommandAction on TextBox inside ListView MVVM)

问题在于x:文本框的绑定。 它的模式是单向的。 因此,文本更改不会反映在视图模型上。 将其更改为Binding。 这也可能导致问题 {x:Bind}不使用DataContext作为默认源 - 而是使用页面或用户控件本身。 因此,它将查看属性,字段和方法的页面或用户控件的代码隐藏。 要将视图模型公开到{x:Bind},您通常需要为页面或用户控件的后台代码添加新字段或属性。 请参阅此链接x:绑定 希望它有效 Problem is with x:Bind of textbox . It's mode i ...

如何使用InvokeCommandAction调用我的方法并传入参数?(How do I go about using InvokeCommandAction to call a method of mine and pass in parameters?)

命令绑定需要一个实现ICommand接口的具体实例。 您绑定到方法名称,它根本不会真正绑定。 命令绑定意味着在MVVM设计中的ViewModel类中使用,但是从您的示例代码中可以看出,您在Xaml视图的代码隐藏中使用它。 如果你想坚持代码隐藏,只需使用事件处理程序。 有关ICommand实现的很多示例,您也可以在Prism中使用现成的DelegateCommand 。 我在下面展示了一个简单的示例,该示例实现了一个非常基本的ICommand,只要您的View和ViewModel已连线,它就可以用于 ...

更改了ContentControl的WPF InvokeCommandAction(WPF InvokeCommandAction with ContentControl Changed)

您应该在PageViewModel属性的setter中处理此问题: private object pageViewModel; public object PageViewModel { get { return pageViewModel; } set { pageViewModel = value; OnPropertyChanged(); MyCommand.Execute(null); } } Content ...

如何在main方法java调用中处理空参数(How to handle empty parameters in a main method java call)

例如,假设最后两个是可选的。 String dType = args[0]; String clientName = args[1]; String cycleString = args[2]; String mspsURL = args[3]; String inputFile = (args.length < 4 ? "default inputFile" : args[4]); String outputFolder = (args.length < 5 ? "default outputF ...

相关文章

更多

最新问答

更多
  • 如何从远程文件拉取文件而不覆盖本地文件?(How do I pull files from remote without overwriting local files?)
  • Reactjs:状态改变时重新渲染iframe(Reactjs: re-renders iframes when state changed)
  • 奇怪的网址,以及跟随php页面流程的困难(odd url, and difficulty in following the php page flow)
  • 标签活动无效(Tab Activity is not working)
  • JavaME合适的语法编译器建议?(JavaME-suitable grammar compiler recommendations?)
  • 指定参数(Specifying arguments)
  • 可以通过Ruby插件或控制台覆盖Sketchup中的键盘快捷键吗?(Can one override keyboard shortcuts in Sketchup through the a Ruby Plugin or Console?)
  • 计算Java EE Web App中用户数的最佳方法(Best way to count number of users in a Java EE web App)
  • 无法使用templateUrl加载cordova中的外部模板(unable to load external templates in cordova with templateUrl)
  • PHPExcel:写入期间无法使用缓存(PHPExcel: Unable to use cache during write)
  • 在javascript中嵌套这个指针(nested this pointer in javascript)
  • 谁跟领航致远培训过,有问题问下啊
  • 控制器要求在入门时下载(Controller ask to download on entry)
  • 未能通过conda安装Asyncio(Failure to install Asyncio via conda)
  • 如何查找已完成项目的总长度?(How to find length of total completed items?)
  • 如何检查OleInitialize是否已被调用?(How to check if OleInitialize has already been called?)
  • SQL在特定范围内返回列中具有最大值的行(SQL Returning rows with max value in column, within a specific range)
  • preg_match从url获取id(preg_match get the id from url)
  • 如何在运算符中为make方程转换perl变量?(How to convert a perl variable in a operator for make equations?)
  • 在导航上方添加空格/标题。(Add a white space/ header above navigation.)
  • MeetingItem已保存;(MeetingItem saved; but change now shown in Calendar)
  • c#vb:我们应该使用System.Lazy进行资源密集型任务吗?(c# vb: Should we use System.Lazy for resource-intensive task? (when threading is not needed))
  • 为什么在armeabi代码中使用armeabi-v7a代码?(Why use armeabi-v7a code over armeabi code?)
  • 获取请求的自定义标头(Java HTTP)(Fetching a custom header of a request (Java HTTP))
  • 是否可以在嵌套的if语句中从varchar转换为numeric以动态评估参数?(Is it possible to convert from varchar to numeric within a nested if statement in order to dynamically evaluate a parameter?)
  • 如何将Html.ActionLink转换为链接到Ajax调用的按钮?(How to convert from Html.ActionLink to a button linked to Ajax call?)
  • 应用程序如何处理Windows符号链接?(How are Windows symbolic links treated by the apps?)
  • html,js,css在jsfiddle中工作,但不在sharepoint中(html, js, css works in jsfiddle but not in sharepoint)
  • 从Ruby脚本调用Elasticsearch Rest API(Calling Elasticsearch Rest API from Ruby script)
  • 如何将嵌套setTimeouts转换为承诺(How to convert nested setTimeouts to promises)