带参数的 RelayCommand
我在我的应用程序中使用 MVVM Light 工具包,并尝试了解如何传递命令。 我有以下 XAML 代码片段:
<s:ScatterView x:Name="swPicture" ItemsSource="{Binding Pictures}" ItemTemplate="{StaticResource Scatter_Thumbnail}"/>
<Button Content="Info" Width="40" Height="40"
Command="{Binding GetInfoCommand}"
Grid.Row="0" HorizontalAlignment="Left"/>
元素 swPicture 包含来自图片集合的项目源。作为暂时的测试,我只有一张图片。
如何将 swPicture 元素中图片中的第一张图片作为参数传递给命令?
目前,我可以使用模型中的以下命令处理程序触发不带参数的单个命令,如下定义:
GetInfoCommand = new RelayCommand<Picture>(
action=>
{
GetMetaData();
},
g=>true); //Execute method
这个想法是我需要将集合中的第一张图片作为参数传递给我的命令,以便将其传递到 GetMetaData 将接受此参数
如何更新我的 XAML 代码和命令以使其工作?
I am using the MVVM Light toolkit in my application and trying to learn about passing a command.
I have the following XAML code snippet:
<s:ScatterView x:Name="swPicture" ItemsSource="{Binding Pictures}" ItemTemplate="{StaticResource Scatter_Thumbnail}"/>
<Button Content="Info" Width="40" Height="40"
Command="{Binding GetInfoCommand}"
Grid.Row="0" HorizontalAlignment="Left"/>
Element swPicture contains items source coming from Pictures collection. As a test only for the time being I just have 1 single picture.
How can I pass as a parameter to the command, the single first picture from the Pictures which is in my swPicture Element ?
For the time being I am able to trigger the single command without parameter with following command handler in the model as defined bellow:
GetInfoCommand = new RelayCommand<Picture>(
action=>
{
GetMetaData();
},
g=>true); //Execute method
The idea is that I need to pass the first Picture from the collection as a parameter to my command in order to pass it to GetMetaData which will have accept this parameter
How can I update my XAML code and the command in order to make it work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的场景中,您根本不需要参数,因为您的视图模型同时具有 Pictures 集合和 GetInfoCommand - GetMetaData 方法可以访问该集合,您只需从那里访问第一个元素。
如果您的问题是如何传递参数 - 您只需将按钮的 CommandParameter 属性的值设置为某个值或将其绑定到您想要的任何值,当您按下按钮时 - Execute 和 CanExecute 方法将将该值传递为一个论点。
In your scenario you don't need a parameter at all, since your view model has both the Pictures collection and the GetInfoCommand - GetMetaData method has access to the collection and you can just access the first element from there.
If your question is how to pass parameters - you can just set the value of the CommandParameter property of your button to some value or bind it to whatever you want and when you press the button - the Execute and CanExecute methods will be passed that value as an argument.
命令参数执行此操作
CommandParameter do this