我想使用帶有 ICommand 的 Tap Gesture Recogniser,意思是使用 ViewModel 而不是背后的代碼。
我正在通過后面的代碼使手勢識別器作業,如下所示
主頁.xaml
<CollectionView Margin="10,0,10,0"
ItemSizingStrategy="MeasureAllItems"
ItemsLayout="VerticalList"
VerticalScrollBarVisibility="Always"
ItemsSource="{Binding QuestionPacks}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="model:QuestionPack">
<Frame Margin="5"
CornerRadius="10">
<Frame.GestureRecognizers>
<TapGestureRecognizer
Tapped="TapGestureRecognizer_Tapped"/>
<TapGestureRecognizer
NumberOfTapsRequired="2"
Tapped="TapGestureRecognizer_Tapped_1"/>
</Frame.GestureRecognizers>
<VerticalStackLayout Margin="5">
<Label Text="{Binding Topic}" />
<Label Text="{Binding TopicId}" />
</VerticalStackLayout>
</Frame>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
請注意x:DataType=model:QuestionPackDataTemplate 中的。
主頁.xaml.cs
private async void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var selectedItem = ((VisualElement)sender).BindingContext as QuestionPack;
if (selectedItem == null)
return;
LoadingQuestions.IsRunning = true;
LoadingQuestions.IsEnabled = true;
await Shell.Current.GoToAsync($"{nameof(QuestionsPage)}?topicSelected={selectedItem.TopicId}");
LoadingQuestions.IsRunning = false;
LoadingQuestions.IsEnabled = false;
}
這作業正常,但我想知道如何在我的 ViewModel 中實作它。在嘗試執行此操作時,我遇到了 2 個挑戰。
我應該在 TapGestureRecognizer 下使用 Command 而不是 Tapped。每當我將 Command 欄位系結到后面代碼中的 Command 時,x:DataType="model:QuestionPack"都會引發問題,因為該命令未在資料模板的模型中定義。
即使將命令應用于點擊手勢識別器不會導致構建應用程式失敗,我如何將被點擊的物件傳遞到后面的代碼中?在后面的代碼中,我使用物件發送器檢索它,但在 ViewModel 中,我不知道。我猜這就是 CommandParameters 發揮作用的地方,但我不知道如何實作它們。
如果有人也可以解釋什么CommandParameter="{Binding .}"意思,請不要打擾。
非常感謝任何幫助。
uj5u.com熱心網友回復:
創建您的 ViewModel 檔案并定義為 BindingContext 示例
<ContentPage.BindingContext>
<vm:MyViewModel />
</ContentPage.BindingContext>
然后在您的 ViewModel 中定義您的 Command 和 ICommand(假設您知道該怎么做)
在你的 xaml 檔案中,你可以做這樣的事情
<Frame.GestureRecognizers>
<TapGestureRecognizer NumberOfTapsRequired="1"
CommandParameter="{Binding .}"
Command="{Binding
Source={RelativeSource AncestorType={x:Type vm:MyViewModel}}, Path=TapGestureRecognizer_Tapped}"/>
</Frame.GestureRecognizers>
告訴我更多細節
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/481177.html
