首页 \ 问答 \ 如何使用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>
2015-05-28

相关文章

更多

最新问答

更多
  • 如何保护Solr只允许SELECT请求给用户并禁止其他任何东西?(How to secure Solr to allow SELECT request to only users and disallow anything else?)
  • XPath表达式无效/错误TFHpple SWIFT 1.2(XPath Expression not working/incorrect TFHpple SWIFT 1.2)
  • css3 3D变换不能平滑地制作动画(css3 3D transform doesn't animate smoothly)
  • 运行时错误'91'和Outlook.Application = <对象变量或没有设置块变量>?(Run-time error '91' & Outlook.Application = Object variable or With block variable not set?)
  • 慢的webservice问题(Slow webservice problem)
  • textview的不正确对齐方式(Improper alignment of a textview)
  • 在第一步“Hello World”中出现Java错误(Cannot run “Hello World” program in Eclipse)
  • 为什么十六进制地址是14个字符?(why the hex address is 14 character?)
  • 如何在Python中的不同类中使用变量?(How to use variable in different classes in Python?)
  • asp:GridView HYPERLINKFIELD - datanavigateurlformatstring中的asp代码(asp:GridView HYPERLINKFIELD - asp code inside datanavigateurlformatstring)
  • 关于adaboost算法(About adaboost algorithm)
  • 在Matlab上内置图像(Built in Images on Matlab)
  • java swing:输入键事件时焦点丢失(java swing: Focus lost on enter key event)
  • C#中的通用约束,T是相同的TSomethingElse,对吧?(Generic constraints in C#, T is the same TSomethingElse, right?)
  • 从mybatis中的光标获取数据(Fetching data from cursor in mybatis)
  • 在运行时从XML构建对象的最佳方法(Best way for building objects out of XMLs at runtime)
  • 在整个窗口中拉伸sf :: Sprite(Stretch sf::Sprite across entire window)
  • Selenium Node API Web驱动程序等待超时处理程序(Selenium Node API web driver wait timeout handler)
  • 函数使用并且是map的一部分(循环依赖?)(Function uses and is part of map (circular dependency?))
  • 是否可以在C ++ 14中使用可选模板参数创建类型元组?(Is possible to make a tuple of types with optional template parameters in C++14?)
  • PHP从窗帘后面打印/ f(PHP prints /f from behind the curtains)
  • JFrame的contentPane的LayoutManager(LayoutManager of JFrame's contentPane)
  • 用于Instagram Feed的图像滚动(Image Roll Overs for Instagram Feed)
  • 如何显示拉伸字体(双倍宽度/高度)?(How to display stretched font (double width/height)?)
  • 文件操作API在fileapi.h和stdio.h中的WP8差异?(WP8 differences between file manipulation APIs in fileapi.h and stdio.h?)
  • 保存失败后Rails没有回滚事务()(Rails not rolling back transaction after failed save())
  • jqgrid中的分页问题与数组数据(Pagination problem in jqgrid with array data)
  • 重定向时,通过其他页面上的URL调用javascript函数(Call javascript function through url on otherpage while Redirecting)
  • 如何使用InvokeCommandAction调用我的方法并传入参数?(How do I go about using InvokeCommandAction to call a method of mine and pass in parameters?)
  • Jquerymobile按钮仅显示页面的第一个外观(Jquerymobile buttons are shown only first apperance of the page)