【问题标题】:Pass three parameters to Prism DelegateCommand to use the same command on different button commands [MVVM mode]将三个参数传递给 Prism DelegateCommand 以在不同的按钮命令上使用相同的命令 [MVVM 模式]
【发布时间】:2020-10-20 13:26:15
【问题描述】:

我有以下使用 Prism 库创建的 DelegateCommand。

public class AddressModel : INotifyPropertyChanged
{
    public ICommand MyButtonClickCommand
    {
        get { return new DelegateCommand<object>(FuncToCall); }
    }

    public void FuncToCall(object context)
    {
        //this is called when the button is clicked
        Method1("string1", integer_number1);
    }
}

我已经将MyButtonClickCommand 绑定到 XAML 文件中的按钮。

<Button Content="Click me" 
        Command="{Binding MyButtonClickCommand}"/> 

但我想将相同的MyButtonClickCommand 用于另外两个按钮,而不是创建两个额外的 DelegateCommands MyButtonClickCommand1MyButtonClickCommand2

所以我想要添加 string1integer_number1 作为参数,并在不同的按钮上调用相同的 ICommand,如下所示

<Button Content="Click me" 
        Command="{Binding MyButtonClickCommand("string1", integer_number1)}"/>
<Button Content="Click me 2" 
        Command="{Binding MyButtonClickCommand("string2", integer_number2)}"/>
<Button Content="Click me 3" 
        Command="{Binding MyButtonClickCommand("string3", integer_number3)}"/>

【问题讨论】:

  • 您可以将单个对象传递给 Button 的 CommandParameter 属性,例如通过绑定或直接分配。该对象作为参数传递给命令的 Execute 处理程序方法。
  • @Clemens 感谢您的评论。但是 Execute 处理程序如何知道“string1”和 integer_number1 放在 FuncToCall() 内的什么位置?
  • @Clemens 我也认为我不能使用超过 1 次 CommandParameter。根据我的问题,我有 2 个参数要传入 DelegateCommand

标签: c# wpf prism delegatecommand


【解决方案1】:

您可以传递可以在 XAML 中声明的任何类的实例

public class MyCommandParameter
{
    public int MyInt { get; set; }
    public string MyString { get; set; }
}

到按钮的CommandParameter 属性:

<Button Content="Click me" Command="{Binding ...}">
    <Button.CommandParameter>
        <local:MyCommandParameter MyInt="2" MyString="Hello"/>
    </Button.CommandParameter>
</Button>

MyCommandParameter 实例被传递给 Execute 处理程序方法的参数:

public void FuncToCall(object parameter)
{
    var param = (MyCommandParameter)parameter;

    // do something with param.MyInt and param.MyString
}

【讨论】:

    【解决方案2】:

    使用CommandParameter 属性:

    <Button Content="Click me 2" 
            Command="{Binding MyButtonClickCommand}"
            CommandParameter="2" />
    

    然后您可以将context 参数转换为命令参数的值:

    public void FuncToCall(object context)
    {
        string parameter = context as string;
        if (int.TryParse(parameter, out int number))
        {
            //---
        }
    }
    

    【讨论】:

    • 谢谢mm8,虽然我需要同时传递两个不同的参数(即“string2”和integer_number2)。我想我不能多次使用 CommandParameter。
    • 那么像列表猜测?
    • 就像一个有两个属性的类。有关示例,请参见其他答案。
    • 好的,让我尝试创建一个有两个参数的类并将该类传递给object context。我很高兴我的问题至少很清楚:)
    • @DelusionX:请参阅其他答案以获取示例。
    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 2010-09-11
    • 2023-03-23
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    相关资源
    最近更新 更多