【问题标题】:RelayCommand with parameters带参数的 RelayCommand
【发布时间】:2012-01-05 20:12:25
【问题描述】:

我在我的应用程序中使用 MVVM Light 工具包并尝试了解如何传递命令。 我有以下 XAML 代码 sn-p:

<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 代码和命令以使其正常工作?

【问题讨论】:

    标签: wpf binding mvvm mvvm-light relaycommand


    【解决方案1】:

    在您的场景中,您根本不需要参数,因为您的视图模型同时具有 Pictures 集合和 GetInfoCommand - GetMetaData 方法可以访问该集合,并且您可以从那里访问第一个元素。

    如果您的问题是如何传递参数 - 您可以将按钮的 CommandParameter 属性的值设置为某个值或将其绑定到您想要的任何值,当您按下按钮时 - 将传递 Execute 和 CanExecute 方法该值作为参数。

    【讨论】:

      【解决方案2】:

      CommandParameter 这样做

      <s:ScatterView x:Name="swPicture" ItemsSource="{Binding Pictures}" ItemTemplate="{StaticResource Scatter_Thumbnail}"/>
          <Button Content="Info" Width="40" Height="40"
                               Command="{Binding GetInfoCommand}" CommandParameter="{Binding Pictures[0]}"
                                 Grid.Row="0" HorizontalAlignment="Left"/>
      

      【讨论】:

        猜你喜欢
        • 2013-10-28
        • 1970-01-01
        • 1970-01-01
        • 2019-03-02
        • 1970-01-01
        • 2014-03-30
        • 1970-01-01
        • 2015-10-27
        相关资源
        最近更新 更多