首页 > 解决方案 > 事件到命令行为不执行命令

问题描述

我正在使用此处找到的事件到命令行为来实现 ListView 的 ItemTapped 事件中的命令。我将 EventToCommandBehavior 和 BehaviorBase 类复制到我的项目中。

这是我的看法

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:d="http://xamarin.com/schemas/2014/forms/design"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:local="clr-namespace:AppVentas.Behaviors"
         mc:Ignorable="d"
         x:Class="AppVentas.Views.UsuariosView">
<ContentPage.Content>
    <ListView HasUnevenRows="True"
              ItemsSource="{Binding Usuarios}"
              ItemTapped="ListView_ItemTapped">
        <ListView.Behaviors>
            <local:EventToCommandBehavior 
                EventName="ItemTapped" 
                Command="{Binding OpenChatCommand}"/>
        </ListView.Behaviors>
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Label Text="{Binding Nombre}"/>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>

还有我的 ViewModel

public class UsuariosViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<Usuarios> Usuarios { get; set; }
    public ICommand OpenChatCommand { get; set; }

    private UsuarioController usuarioController = new UsuarioController();

    public UsuariosViewModel()
    {
        Usuarios = new ObservableCollection<Usuarios>(usuarioController.Get().Where(i => i.Token == null));

        OpenChatCommand = new Command<Usuarios>(OpenChat);
    }


    void OpenChat(Usuarios usuario)
    {
        //trying to do something
    }
}

问题是 OpenChatCommand 永远不会被执行,EventToCommandBehavior 类的 OnEvent 方法会被执行,但是 Command.Execute (resolvedParameter); 行 只是什么都不做。

如果有任何用处,我正在使用 PropertyChanged.Fody 包。

任何帮助表示赞赏,谢谢。

标签: c#mvvmxamarin.forms

解决方案


假设您的 bindingcontext 正确设置为 UsuariosViewModel 的实例,我在这里看到的问题是您没有传递命令参数。您的命令接受一个 Usuarios,但您需要通过 EventToCommandBehavior 上的 CommandParameter 属性将其传入。

我还注意到您定义了 ListView_ItemTapped,但我不确定您在该方法中做了什么。它不应该是使命令工作所必需的,但也许您正在将它用于其他用途。


推荐阅读