2017-09-05 30 views
0

我有這樣一個標籤:我怎樣才能手勢識別器添加到視圖模型C#

<Label Grid.Row="1" Grid.Column="0" x:Name="faveLabel" Style="{StaticResource smallIcon}" FontFamily="FontAwesome" VerticalOptions="FillAndExpand" VerticalTextAlignment="Center" /> 

,並在C#的背後,我有:

faveLabel.GestureRecognizers.Add(
      new TapGestureRecognizer() 
      { 
       Command = new Command(() => 
       { 
        App.phrase.Favorite = !App.phrase.Favorite; 
        faveLabel.TextColor = App.phrase.Favorite == true ? Color.Red : Color.Gray; 
        App.DB.UpdateFavorite(App.phrase.Favorite, App.phrase.PhraseId); 
       }) 
      }); 

正如我綁定一個視圖模型來這個框架,那麼我怎樣才能將這個視圖移到這個viewModel代碼中?

public class PhrasesFrameViewModel : ObservableProperty 
{ 
    public PhrasesFrameViewModel() 
    { 

     var aButtonClickedCommand = new Command(() => 
     { 
      App.DB.IncrementScore(App.cfs, App.phrase, (int)App.aBtn); 
      App.correctButtonPressed = (int)App.aBtn; 
      ResetTimer2(); 
     }); 

注意,我真的想避免增加手勢識別到XAML的XAML已經是相當大的。

回答

3

您可以綁定到Xamarin.Forms的最新版本的命令,所以你可以做一些事情,像這樣:

您的視圖模型:

public class PhrasesFrameViewModel : ObservableProperty 
{ 
    public PhrasesFrameViewModel() 
    { 

     var aButtonClickedCommand = new Command(() => 
     { 
      App.DB.IncrementScore(App.cfs, App.phrase, (int)App.aBtn); 
      App.correctButtonPressed = (int)App.aBtn; 
      ResetTimer2(); 
     }); 

XAML中:

<Label.GestureRecognizers> 
    <TapGestureRecognizer Command="{Binding aButtonClickedCommand}"/> 
</Label.GestureRecognizers> 

這應該將viewmodel中的命令綁定到您的標籤。

+0

謝謝,如果您有一些時間可以解釋一點關於您使用的單獨課程的更多信息。你是否在說,你不會把水龍頭手勢放入視圖模型中,如果是這種情況,那麼你如何綁定它們? – Alan2

+1

@ Alan2道歉Alan,忽略行爲評論(我已經刪除了它)。這更適用於驗證條目等。想想我今天一直努力工作,哈哈,繼承人與Xamarin行爲之間的聯繫,只是說明你想看看他們做什麼:https://blog.xamarin.com/行爲功能於xamarin表單/ – Digitalsa1nt

相關問題