2017-07-04 48 views
0

我的代碼如下。我不知道命令是否正確執行ToolbarItem。編譯沒有錯誤。當點擊了baritem時,什麼也沒有發生。ToolBar中的Toolbaritem不點擊

--- Xaml 

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"   
      xmlns:local ="clr-namespace:SembIWIS.View" 
      BackgroundColor="White" 
      Title="Repair and Service"   
      x:Class="MyMainMenu"> 
    <ContentPage.ToolbarItems> 
     <ToolbarItem Name="MenuItem1" Order="Primary" Icon="itemIcon1" Command="{Binding Item1Command}" Priority="0" /> 
     <ToolbarItem Name="MenuItem2" Order="Primary" Icon="itemIcon2" Priority="1" /> 
    </ContentPage.ToolbarItems> 

    <local:Product> 
    </local:Product> 

    <local:Service> 
    </local:Service> 

</TabbedPage> 


--------- Code Behind: 

public partial class MyMainMenu : TabbedPage 
    { 
     public ICommand Item1Command { get; private set; } 

     public MyMainMenu() 
     { 
      InitializeComponent(); 

      BindingContext = this; 

      NavigationPage.SetHasBackButton(this, true); 
      Init(); 
     } 

     private void Init() 
     { 

      this.Item1Command = new Command((sender) => 
      { 
       Navigation.PushAsync(new UpdateProduct()); 
      }); 


} 
+0

你還沒有爲你的視圖設置綁定上下文,所以'Command =「{Binding Item1Command}」'沒有綁定任何東西。一個短期的解決方法是在'MyMainMenu'構造函數中設置綁定上下文:'BindingContext = this;',儘管您可能想要調查MVVM模式並將您的ViewModel移動到一個對UI不瞭解的單獨的類。 – Damian

+0

這是在同一頁面上完成的。你能否向我展示如何以及在何處添加綁定上下文。 – MilkBottle

+0

我更新了我的評論以解釋(我過早地輸入)。 – Damian

回答

0

從評論我收集你忘了添加BindingContext。雖然您現在確實添加了它,但時機不對。在設置BindingContext之前,您需要執行Init();方法。

當設置了BindingContext時,此時一切都會接通,除非您正確實施INotifyPropertyChanged接口,否則您所做的任何更改都不會被提取。總之,對於這個問題,適應您的代碼如下:

public MyMainMenu() 
{ 
    InitializeComponent(); 

    NavigationPage.SetHasBackButton(this, true); 
    Init(); 

    BindingContext = this; 
} 

在評論關於你的問題,關於性能和單元測試:

沒有性能上的差異,因爲兩者MVVM框架您將使用意願執行這個非常相同的代碼,只會自動爲你做。如果有的話,MVVM框架可能會慢一點,因爲它可能會通過反射或類似的方式解析您的ViewModels。如果你想做單元測試,你將不得不將你的代碼分解成一個單獨的ViewModel,並將其設置爲你的BindingContext。例如看看這個blog post關於使用FreshMvvm與單獨的Views和ViewModels。

+0

只是一個想法。比較這種方法和Mvvm Binding for命令,這對於單元測試更容易?是否有任何性能差異? – MilkBottle

+0

我已經用這個答案更新了問題 –