在Xamarin.Forms中,按钮命令绑定未调用绑定的命令

5

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

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

我使用的手势识别器命令正常工作,只有按钮似乎不起作用,我尝试在被调用的方法中添加Debug.WriteLine()以查看它们是否执行,但它们从未写入输出日志,因此我认为它们根本没有被调用。
那么,按钮不调用其命令的原因是什么?

1个回答

11

看起来,CommandListViewBindingContext 中寻找 SaveItemData。但是你的命令放置在 ViewModel 中。 我想提供我的解决方案:

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

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


按钮有效地查找了ListView的BindingContext,谢谢! - Pazgabear

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接