我需要更改我们编写的 WPF 应用程序中的某些功能。我们使用 MVVM Light 来实现 MVVM。每当我们需要将一些参数传递给我们使用 MVVM Light 的 Messenger 类的方法时。我必须将 3 个参数传递给一个方法,但我想我会尝试在不使用 Messenger 类的情况下执行此操作,但我希望我可以使用 RelayCommand() 方法来执行此操作。我搜索了一下,发现 this post从几年前开始就在这里。但至少对我来说,我认为这不会起作用,因为它只使用一种类型;在这种情况下是字符串。在做了一些试验并意识到我做错了之后,我决定我可以创建一个类,其中包含我需要的 3 个值作为类的属性,将其放入 Models 文件夹并使用
new RelayCommand<MyClass>()
所以,第一个问题,只是为了验证我的想法是否正确,我想我会做这样的事情:
new RelayCommand<MyClass>((mc) => MyMethod(mc.Prop_A, mc.Prop_B, mc.Prop_C)
对吗?
假设上面的答案是肯定的,那么当我在 XAML 中绑定(bind)到它时,我如何实际将参数传递给它?此命令将与窗口/页面上的按钮相关联,因此我将使用按钮的命令属性。我如何实际传递 MyClass 实例 Prop_A、Prop_B 和 Prop_C 的值?
最佳答案
So, first question, just to verify that I've got the right idea, I think I would do something like this:
new RelayCommand<MyClass>((mc) => MyMethod(mc.Prop_A, mc.Prop_B, mc.Prop_C)
这是正确的。
Assuming the answer to the above is yes, then how do I actually pass parameters to this when I bind to it in the XAML? This command is going to be associated with a button on the window/page, so I'll be using the Button's Command property. How do I actually pass in the values for the MyClass instances Prop_A, Prop_B and Prop_C?
这实际上取决于 Prop_A、Prop_B 和 Prop_C 的来源。如果这些属性已在您的 View 模型中,则无需使用 XAML 传递参数。
new RelayCommand<MyClass>((mc) => MyMethod(mc.Prop_A, mc.Prop_B, mc.Prop_C)
将更改为
new RelayCommand<object>((param) =>
{
// param is not used.
var mc = this.MC; // assuming your view model holds the mc value
MyMethod(mc.Prop_A, mc.Prop_B, mc.Prop_C);
});
我们必须确保当我们加载我们的 View 模型时,我们拥有我们需要的一切。否则,使用 IoC
来获取您需要的任何内容。
将参数绑定(bind)到您的命令通常对像计算器应用程序这样的东西很有用,您可以在其中将按钮值传递给您的命令,例如 0 - 9。
<Button Grid.Row="0" Grid.Column="1" Content="7" Command="{Binding PerformAction}" CommandParameter="7"/>
我不想在您看来定义类。对于关注点分离, View 应该只知道要绑定(bind)到的属性,而不是模型。
关于c# - 如何使用多个参数调用 RelayCommand?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46965981/