我目前正在创建一个页面,使用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()以查看它们是否执行,但它们从未写入输出日志,因此我认为它们根本没有被调用。
那么,按钮不调用其命令的原因是什么?