Use RelayCommand with not only buttons

佐手、 提交于 2020-01-06 17:59:51

问题


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).

Here is my current code:

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

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.

What does MVVM Light offer to do in such cases?


回答1:


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>

Custom converter class

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();
    }
}

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.   
}

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

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


来源:https://stackoverflow.com/questions/29586439/use-relaycommand-with-not-only-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!