无法使用 ReactiveUI 将列表视图中的按钮绑定到 ViewModel

Can't bind a button in a listview to ViewModel using ReactiveUI

我正在使用 ReactiveUI 将按钮绑定到 ReactiveCommand,但它没有响应,所以我在这里错过了什么??

这是 LikeCommand

     LikesCommand = ReactiveCommand.Create<Button>(LikeChanges);


private void LikeChanges(Button sender)
    {
        sender.Clicked += (s, e) =>
        {
            _newsFeed.LikesNum++;
            _newsFeed.BackgroundColor = Color.White;
            _newsFeed.TextColor = Color.DodgerBlue;
            RaisePropertyChanged();
        };
    }

这是删除命令

 DeleteCommand = ReactiveCommand.Create<NewsFeed>(DeleteItem);

     public async void DeleteItem(NewsFeed news)
    {
        var res = await CoreMethods.DisplayAlert("OH !", "Are you sure?", 
                 "Yes", "No");
        if (res)
        {
            NewsFeeds.Remove(news);
            RaisePropertyChanged();
        }

    }

这是我在列表视图中的 viewCell 中的按钮

     <Button Text="{Binding LikesNum , StringFormat='Like {0}'}"
           x:Name="btnLike"
           Command="{Binding LikesCommand}"
           BackgroundColor="{Binding BackgroundColor}"
           TextColor="{Binding TextColor}"
           HorizontalOptions="StartAndExpand" />
      <Button Text="Delete"
            x:Name="btnLike"
           Clicked="Button_OnClicked"
           Command="{Binding DeleteCommand}"
           HorizontalOptions="End" />                          

几个问题。

Create 上的泛型用于命令参数,但您尚未定义。通常,您会将所选元素绑定到视图模型。

创建遗嘱是在您执行以下操作时:

<Button Command="{Binding DeleteCommand, Mode=OneWay}" CommandParameter="{Binding ElementName=ListBox, Name=SelectedItem}" />

Create 中的 T 与您通过 CommandParameter 传入的类型相匹配。另一种方法是在您的 ViewModel 上有一个名为 SelectedItem 的 属性,然后将 SelectedItem 绑定到 属性.

您可能需要{Binding DeleteCommand, Mode=OneWay}

避免返回 async void,而是执行 public async Task 并改用 CreateFromTask 重载。

您的按钮上有一个点击和命令。你想要一个。

另请参阅 https://reactiveui.net/docs/handbook/commands/ 获取更多创意。

同时考虑使用 reactiveui 绑定。