我目前正在使用 ListView 创建一个页面,该页面由我从 Web API 恢复的数据填充。
我添加了 2 个按钮:一个用于刷新数据,一个用于将数据本地存储在设备上。问题是:它们都不起作用,绑定(bind)不会在日志中产生错误,所以我猜它确实将命令绑定(bind)到按钮,但是当我点击它时,命令没有被调用。
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() 放在调用的方法中以查看它们是否正在执行,但它们从未写入输出日志,所以我假设他们根本没有被调用。
那么,按钮不调用其命令的原因可能是什么?
最佳答案
看起来,Command
在 ListView
的 BindingContext
中寻找 SaveItemData
。但是您的命令放在 ViewModel 中。
我想向您推荐我的解决方案:
<Button Command="{Binding BindingContext.YourCommand, Source={x:Reference Page}"
CommandParameter="{Binding BindingContext, Source={x:Reference SomeControl}"/>
对我有用,希望对你有帮助!
关于c# - 按钮命令绑定(bind)不调用 Xamarin.Forms 中的绑定(bind)命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35913622/