按钮命令绑定不调用 Xamarin.Forms 中的绑定命令

Button command binding not calling the binded command in Xamarin.Forms

我目前正在使用 ListView 创建一个页面,该页面由我从 Web 恢复的数据填充 API。
我添加了 2 个按钮:一个用于刷新数据,一个用于将数据本地存储在设备上。问题是:none 它们工作,绑定不会在日志中产生错误所以我猜它确实将命令绑定到按钮,但是当我点击它时,命令没有被调用。

XAML

<ListView ItemsSource="{Binding Items}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <StackLayout.GestureRecognizers>
                        <TapGestureRecognizer CommandParameter="{Binding ItemId}">
                            <TapGestureRecognizer.Command>
                                <Binding Source="{x:Reference Page}">
                                    <Binding.Path>BindingContext.ShowItemDataCommand</Binding.Path>
                                </Binding>
                            </TapGestureRecognizer.Command>
                        </TapGestureRecognizer>
                    </StackLayout.GestureRecognizers>
                    <Switch IsToggled="{Binding IsOffline}"/>
                    <StackLayout Orientation="Vertical">
                        <Label Text="{Binding ItemTitle}"/>
                        <Label Text="{Binding ItemDescription}" FontSize="Micro"/>
                    </StackLayout>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
<ListView.Footer>
    <StackLayout>
        <Button Text="Refresh items" HorizontalOptions="CenterAndExpand" Command="{Binding RefreshItemsCommand}"/>
        <Button Text="Save item data" HorizontalOptions="CenterAndExpand" Command="{Binding SaveItemData}"/>
    </StackLayout>
</ListView.Footer>
</ListView>

ViewModel 中的命令

public class ItemsViewModel : INotifyPropertyChanged
{
    (...)
    public ItemsViewModel() {
        (...)
        RefreshItemsCommand = new Command(GetItemsObservableCollection);
        TogglePacksAvailabilityCommand = new Command(async () =>
        {
            foreach (var i in Items.Where(i => i.IsOffline)) {
                await SaveItem(i.ItemId);
            }
        });
        (...)
    }
    (...)
    public ICommand RefreshItemsCommand { protected set; get; }
    public ICommand TogglePacksAvailabilityCommand { protected set; get; }
    (...)
}

我用于 GestureRecognizer 的命令工作正常,只有按钮似乎不起作用,我试图将 Debug.WriteLine() 放在被调用的方法中以查看它们是否正在执行,但它们从未写入输出日志,所以我假设它们根本没有被调用。
那么,按钮不调用其命令的原因可能是什么?

似乎 CommandListViewBindingContext 中寻找 SaveItemData。但是您的命令放在 ViewModel 中。 我想向您推荐我的解决方案:

<Button Command="{Binding BindingContext.YourCommand, Source={x:Reference Page}"
        CommandParameter="{Binding BindingContext, Source={x:Reference SomeControl}"/>

对我有用,希望对你有帮助!