不仅通过按钮使用RelayCommand [英] Use RelayCommand with not only buttons

查看:103
本文介绍了不仅通过按钮使用RelayCommand的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用了MVVM Light,我想知道是否可以通过所有控件(例如ListView或Grid)使用RelayCommand.

I am using MVVM Light in my project and I am wondering if there is any way to use RelayCommand with all controls (ListView or Grid, for example).

这是我当前的代码:

private void Item_Tapped(object sender, TappedRoutedEventArgs e)
{
    var currentItem = (TechItem)GridControl.SelectedItem;
    if(currentItem != null)
        Frame.Navigate(typeof(TechItem), currentItem);
}

我想将此代码移至Model并使用RelayCommand,但是ListView,Grid和其他控件没有CommandCommandParameter属性.

I want to move this code to Model and use RelayCommand, but the ListView, Grid and other controls don't have Command and CommandParameter attributes.

在这种情况下,MVVM Light提供了什么功能?

What does MVVM Light offer to do in such cases?

推荐答案

在har07发布的链接之后,当您看到CommandParameter时,这可能对您有用.

Following on from the link har07 posted this might be of some use to you as I see you mention CommandParameter.

可以使用自定义转换器将列表中的已轻击"项作为参数发送到中继命令.

It is possible to send the "Tapped" item in the list to the relay command as a parameter using a custom converter.

<ListView
    x:Name="MyListView"
    ItemsSource="{Binding MyCollection}"
    ItemTemplate="{StaticResource MyTemplate}"
    IsItemClickEnabled="True">

    <i:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="ItemClick">
             <core:InvokeCommandAction Command="{Binding ViewInMoreDetail}" InputConverter="{StaticResource TapConverter}" />
        </core:EventTriggerBehavior>
    </i:Interaction.Behaviors>

</ListView>

自定义转换器类

public class TapConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var args = value as ItemClickEventArgs;

        if (args != null)
            return args.ClickedItem;

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

在您的视图模型中,您会有一个relaycommand.

In your view model you then have a relaycommand.

public RelayCommand<MyObject> MyRelayCommand
{
    get;
    private set;
}

在构造函数中初始化中继命令和发生轻击时要触发的方法.

In your constructor initialise the relay command and the method you want to fire when a tap happens.

MyRelayCommand = new RelayCommand<MyObject>(HandleTap);

此方法接收已在列表视图中点击的对象作为参数.

This method receives the object that has been tapped in the listview as a parameter.

private void HandleTap(MyObject obj)
{
    // obj is the object that was tapped in the listview.   
}

不要忘记将TapConverter添加到您的App.xaml

Don't forget to add the TapConverter to your App.xaml

<MyConverters:TapConverter x:Key="TapConverter" />

这篇关于不仅通过按钮使用RelayCommand的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆