2016-06-24 32 views
0

我創建了一個簡單的內容頁面來測試各種事件。在ViewModel中重寫OnBackButtonPressed時,不會引發該事件。根據Xamarin的說法,這個事件不會在iOS上提出,但它應該在Android和WP上工作。但我無法在這些平臺上工作。OnBackButtonPressed未在ViewModel中觸發

我錯過了什麼?

TestPage.xaml

<?xml version="1.0" encoding="utf-8" ?> 
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
      x:Class="TestPage.TestPage" 
      Title="testPage"> 
</ContentPage> 

TestPage.xaml.cs

public partial class TestPage : ContentPage 
{ 
    public TestPage() 
    { 
     InitializeComponent(); 
     this.BindingContext = new TestPageViewModel(); 
    } 
} 

視圖模型

public class TestPageViewModel : ContentPage, INotifyPropertyChanged 
{ 
    public TestPageViewModel() { } 
    protected override bool OnBackButtonPressed() 
    { 
     // Do stuff 
     return base.OnBackButtonPressed(); 
    } 
} 

回答

1

在Xamarin論壇上得到了答案。我必須把OnBackPressed覆蓋在我的xaml文件的代碼隱藏中,而不是在我的視圖模型中:

public partial class MyPage2 : ContentPage 
{ 
    public MyPage2() 
    { 
     InitializeComponent(); 
     this.BindingContext = new TestPageViewModel(); 
    } 

    protected override bool OnBackButtonPressed() 
    { 
     // Do stuff 
     return base.OnBackButtonPressed(); 
    } 
} 
+0

其工作正常...很好。 – GvSharma