c# - 事件到命令行为不执行命令
问题描述
我正在使用此处找到的事件到命令行为来实现 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 包。
任何帮助表示赞赏,谢谢。
解决方案
假设您的 bindingcontext 正确设置为 UsuariosViewModel 的实例,我在这里看到的问题是您没有传递命令参数。您的命令接受一个 Usuarios,但您需要通过 EventToCommandBehavior 上的 CommandParameter 属性将其传入。
我还注意到您定义了 ListView_ItemTapped,但我不确定您在该方法中做了什么。它不应该是使命令工作所必需的,但也许您正在将它用于其他用途。
推荐阅读
- assembly - 如何在 8086 汇编语言中将 AX 寄存器的内容移动到 CS 寄存器
- tcp - 如何避免来自服务器的 [RST] 数据包?
- c# - 如何在 WPF(mvvm) 中创建倒计时栏动画,动态宽度和值绑定到视图模型?
- c++ - 项目参考上的 QT 访问冲突
- php - !empty($variable) 和 count($variable) 在 PHP 中的布尔结果是否总是相等?
- aws-amplify - 如何更新 AWS Amplify 中的嵌套 cloudformation 堆栈
- xcode - Xcode 在拆分视图中处理两个项目
- node.js - 在 Node.js 上使用 sharp with discordie,旧图像在后续运行中出现在输出中,损坏在哪里?
- android - Json 数据未在 ListView 中显示
- vue.js - 重新编码一个html